File: NSString.m

package info (click to toggle)
gnustep-base 1.28.1%2Breally1.28.0-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 28,008 kB
  • sloc: objc: 223,137; ansic: 35,562; sh: 184; makefile: 128; cpp: 122; xml: 32
file content (6537 lines) | stat: -rw-r--r-- 177,061 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
/** Implementation of GNUSTEP string class
   Copyright (C) 1995-2012 Free Software Foundation, Inc.

   Written by:  Andrew Kachites McCallum <mccallum@gnu.ai.mit.edu>
   Date: January 1995

   Unicode implementation by Stevo Crvenkovski <stevo@btinternet.com>
   Date: February 1997

   Optimisations by Richard Frith-Macdonald <richard@brainstorm.co.uk>
   Date: October 1998 - 2000

   This file is part of the GNUstep Base Library.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free
   Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110 USA.

   <title>NSString class reference</title>
   $Date$ $Revision$
*/

/* Caveats:

   Some implementations will need to be changed.
   Does not support all justification directives for `%@' in format strings
   on non-GNU-libc systems.
*/

/*
   Locales somewhat supported.
   Limited choice of default encodings.
*/

#define GS_UNSAFE_REGEX 1
#import "common.h"
#include <stdio.h>

#import "Foundation/NSAutoreleasePool.h"
#import "Foundation/NSCalendarDate.h"
#import "Foundation/NSDecimal.h"
#import "Foundation/NSArray.h"
#import "Foundation/NSCharacterSet.h"
#import "Foundation/NSException.h"
#import "Foundation/NSValue.h"
#import "Foundation/NSDictionary.h"
#import "Foundation/NSFileManager.h"
#import "Foundation/NSPortCoder.h"
#import "Foundation/NSPathUtilities.h"
#import "Foundation/NSRange.h"
#import "Foundation/NSRegularExpression.h"
#import "Foundation/NSException.h"
#import "Foundation/NSData.h"
#import "Foundation/NSURL.h"
#import "Foundation/NSMapTable.h"
#import "Foundation/NSLocale.h"
#import "Foundation/NSLock.h"
#import "Foundation/NSNotification.h"
#import "Foundation/NSScanner.h"
#import "Foundation/NSUserDefaults.h"
#import "Foundation/FoundationErrors.h"
// For private method _decodePropertyListForKey:
#import "Foundation/NSKeyedArchiver.h"
#import "GNUstepBase/GSMime.h"
#import "GNUstepBase/NSString+GNUstepBase.h"
#import "GNUstepBase/NSMutableString+GNUstepBase.h"
#import "GSPrivate.h"
#import "GSPThread.h"
#include <sys/stat.h>
#include <sys/types.h>

#if	defined(HAVE_SYS_FCNTL_H)
#  include	<sys/fcntl.h>
#elif	defined(HAVE_FCNTL_H)
#  include	<fcntl.h>
#endif

#include <stdio.h>
#include <wchar.h>

#ifdef HAVE_MALLOC_H
#  ifndef __OpenBSD__
#    include <malloc.h>
#  endif
#endif
#ifdef HAVE_ALLOCA_H
#include <alloca.h>
#endif
#if	defined(HAVE_UNICODE_UCOL_H)
# include <unicode/ucol.h>
#endif
#if	defined(HAVE_UNICODE_UNORM2_H)
# include <unicode/unorm2.h>
#endif
#if     defined(HAVE_UNICODE_USTRING_H)
# include <unicode/ustring.h>
#endif
#if     defined(HAVE_UNICODE_USEARCH_H)
# include <unicode/usearch.h>
#endif

/* Create local inline versions of key functions for case-insensitive operations
 */
#import "Additions/unicode/caseconv.h"
static inline unichar
uni_toupper(unichar ch)
{
  unichar result = gs_toupper_map[ch / 256][ch % 256];
  return result ? result : ch;
}
static inline unichar
uni_tolower(unichar ch)
{
  unichar result = gs_tolower_map[ch / 256][ch % 256];
  return result ? result : ch;
}

#import "GNUstepBase/Unicode.h"

@interface	NSScanner (Double)
+ (BOOL) _scanDouble: (double*)value from: (NSString*)str;
@end

@class	GSString;
@class	GSMutableString;
@class	GSPlaceholderString;
@interface GSPlaceholderString : NSString	// Help the compiler
@end
@class	GSMutableArray;
@class	GSMutableDictionary;

/*
 * Cache classes and method implementations for speed.
 */
static Class	NSDataClass;
static Class	NSStringClass;
static Class	NSMutableStringClass;

static Class	GSStringClass;
static Class	GSMutableStringClass;
static Class	GSPlaceholderStringClass;

static GSPlaceholderString	*defaultPlaceholderString;
static NSMapTable		*placeholderMap;
static pthread_mutex_t          placeholderLock = PTHREAD_MUTEX_INITIALIZER;


static SEL	                cMemberSel = 0;
static NSCharacterSet	        *nonBase = nil;
static BOOL                     (*nonBaseImp)(id, SEL, unichar) = 0;

/* Macro to return the receiver if it is already immutable, but an
 * autoreleased copy otherwise.  Used where we have to return an
 * immutable string, but we don't want to change the parameter from 
 * a mutable string to an immutable one.
 */
#define	IMMUTABLE(S)	AUTORELEASE([(S) copyWithZone: NSDefaultMallocZone()])

static inline BOOL  isWhiteSpace(unichar c)
{
  /* We can not use whitespaceAndNewlineCharacterSet here as this would lead
   * to a recursion, as this also reads in a property list.
   *
   * Copied whitespace and newline index set from  NSCharacterSetData.h
   */
  static const NSRange whitespace[] = {{9,5},{32,1},{133,1},{160,1},{5760,1},{8192,12},{8232,2},{8239,1},{8287,1},{12288,1}};
  unsigned	upper = sizeof(whitespace)/sizeof(*whitespace);
  unsigned	lower = 0;
  unsigned	pos;
  NSRange	r;

  /* Binary search for a range containing the character to be checked
   */
  for (pos = upper/2; upper != lower; pos = (upper+lower)/2)
    {
      r = whitespace[pos];
      if (c < r.location)
        {
          upper = pos;
        }
      else if (c >= NSMaxRange(r))
        {
          lower = pos + 1;
        }
      else
        {
          break;
        }
    }
  return (c >= r.location && c < NSMaxRange(r)) ? YES : NO;
}

#define GS_IS_WHITESPACE(X) isWhiteSpace(X)


/* A non-spacing character is one which is part of a 'user-perceived character'
 * where the user perceived character consists of a base character followed
 * by a sequence of non-spacing characters.  Non-spacing characters do not
 * exist in isolation.
 * eg. an accented 'a' might be represented as the 'a' followed by the accent.
 */
inline BOOL
uni_isnonsp(unichar u)
{
  /* Treating upper surrogates as non-spacing is a convenient solution
   * to a number of issues with UTF-16
   */
  if ((u >= 0xdc00) && (u <= 0xdfff))
    return YES;

  return (*nonBaseImp)(nonBase, cMemberSel, u);
}

/*
 *	Include sequence handling code with instructions to generate search
 *	and compare functions for NSString objects.
 */
#define	GSEQ_STRCOMP	strCompNsNs
#define	GSEQ_STRRANGE	strRangeNsNs
#define	GSEQ_O	GSEQ_NS
#define	GSEQ_S	GSEQ_NS
#include "GSeq.h"

/*
 * The path handling mode.
 */
static enum {
  PH_DO_THE_RIGHT_THING,
  PH_UNIX,
  PH_WINDOWS
} pathHandling = PH_DO_THE_RIGHT_THING;

/**
 * This function is intended to be called at startup (before anything else
 * which needs to use paths, such as reading config files and user defaults)
 * to allow a program to control the style of path handling required.<br />
 * Almost all programs should avoid using this.<br />
 * Changing the path handling mode is not thread-safe.<br />
 * If mode is "windows" this sets path handling to be windows specific,<br />
 * If mode is "unix" it sets path handling to be unix specific,<br />
 * Any other none-null string sets do-the-right-thing mode.<br />
 * The function returns a C String describing the old mode.
 */
const char*
GSPathHandling(const char *mode)
{
  int	old = pathHandling;

  if (mode != 0)
    {
      if (strcasecmp(mode, "windows") == 0)
	{
	  pathHandling = PH_WINDOWS;
	}
      else if (strcasecmp(mode, "unix") == 0)
	{
	  pathHandling = PH_UNIX;
	}
      else
	{
	  pathHandling = PH_DO_THE_RIGHT_THING;
	}
    }
  switch (old)
    {
      case PH_WINDOWS:		return "windows";
      case PH_UNIX:		return "unix";
      default:			return "right";
    }
}

#define	GSPathHandlingRight()	\
  ((pathHandling == PH_DO_THE_RIGHT_THING) ? YES : NO)
#define	GSPathHandlingUnix()	\
  ((pathHandling == PH_UNIX) ? YES : NO)
#define	GSPathHandlingWindows()	\
  ((pathHandling == PH_WINDOWS) ? YES : NO)

/*
 * The pathSeps character set is used for parsing paths ... it *must*
 * contain the '/' character, which is the internal path separator,
 * and *may* contain additiona system specific separators.
 *
 * We can't have a 'pathSeps' variable initialized in the +initialize
 * method because that would cause recursion.
 */
static NSCharacterSet*
pathSeps(void)
{
  static NSCharacterSet	*wPathSeps = nil;
  static NSCharacterSet	*uPathSeps = nil;
  static NSCharacterSet	*rPathSeps = nil;
  if (GSPathHandlingRight())
    {
      if (rPathSeps == nil)
	{
	  (void)pthread_mutex_lock(&placeholderLock);
	  if (rPathSeps == nil)
	    {
	      rPathSeps
		= [NSCharacterSet characterSetWithCharactersInString: @"/\\"];
              rPathSeps = [NSObject leakAt: &rPathSeps];
	    }
	  (void)pthread_mutex_unlock(&placeholderLock);
	}
      return rPathSeps;
    }
  if (GSPathHandlingUnix())
    {
      if (uPathSeps == nil)
	{
	  (void)pthread_mutex_lock(&placeholderLock);
	  if (uPathSeps == nil)
	    {
	      uPathSeps
		= [NSCharacterSet characterSetWithCharactersInString: @"/"];
              uPathSeps = [NSObject leakAt: &uPathSeps];
	    }
	  (void)pthread_mutex_unlock(&placeholderLock);
	}
      return uPathSeps;
    }
  if (GSPathHandlingWindows())
    {
      if (wPathSeps == nil)
	{
	  (void)pthread_mutex_lock(&placeholderLock);
	  if (wPathSeps == nil)
	    {
	      wPathSeps
		= [NSCharacterSet characterSetWithCharactersInString: @"\\"];
              wPathSeps = [NSObject leakAt: &wPathSeps];
	    }
	  (void)pthread_mutex_unlock(&placeholderLock);
	}
      return wPathSeps;
    }
  pathHandling = PH_DO_THE_RIGHT_THING;
  return pathSeps();
}

inline static BOOL
pathSepMember(unichar c)
{
  if (c == (unichar)'/')
    {
      if (GSPathHandlingWindows() == NO)
	{
	  return YES;
	}
    }
  else if (c == (unichar)'\\')
    {
      if (GSPathHandlingUnix() == NO)
	{
	  return YES;
	}
    }
  return NO;
}

/* For cross-platform portability we always use slash as the separator
 * when building paths ... unless specific windows path handling is
 * required.
 * This ensures that standardised paths and anything built by adding path
 * components to them use a consistent separator character anad can be
 * compared readily using standard string comparisons.
 */
inline static unichar
pathSepChar()
{
  if (GSPathHandlingWindows() == NO)
    {
      return '/';
    }
  return '\\';
}

/*
 * For cross-platform portability we always use slash as the separator
 * when building paths ... unless specific windows path handling is
 * required.
 */
inline static NSString*
pathSepString()
{
  if (GSPathHandlingWindows() == NO)
    {
      return @"/";
    }
  return @"\\";
}

/*
 * Find the end of 'root' sequence in a string.  Characters before this
 * point in the string cannot be split into path components/extensions.
 * This usage of the term 'root' is slightly different from the usual in
 * that it includes the first part of any relative path.  The more normal
 * usage of 'root' elsewhere is to indicate the first part of an absolute
 * path.

 * Possible roots are -
 *
 * '/'			absolute root on unix
 * ''			if entire path is empty string
 * 'C:/'		absolute root for a drive on windows
 * 'C:'			if entire path is 'C:' or 'C:relativepath'
 * '//host/share/'	absolute root for a host and share on windows
 * '~/'			home directory for user
 * '~'			if entire path is '~'
 * '~username/'		home directory for user
 * '~username'		if entire path is '~username'
 *
 * Most roots are terminated in '/' (or '\') unless the root is the entire
 * path.  The exception is for windows drive-relative paths, where the root
 * may be a drive letter followed by a colon, but there may still be path
 * components after the root with no path separator.
 *
 * The presence of any non-empty root indicates an absolute path except -
 * 1. A windows drive-relative path is not absolute unless the root
 * ends with a path separator, since the path part on the drive is relative.
 * 2. On windows, a root consisting of a single path separator indicates
 * a drive-relative path with no drive ... so the path is relative.
 */
static unsigned rootOf(NSString *s, unsigned l)
{
  unsigned	root = 0;

  if (l > 0)
    {
      unichar	c = [s characterAtIndex: 0];

      if (c == '~')
	{
	  NSRange	range = NSMakeRange(1, l-1);

	  range = [s rangeOfCharacterFromSet: pathSeps()
				     options: NSLiteralSearch
				       range: range];
	  if (range.length == 0)
	    {
	      root = l;			// ~ or ~name
	    }
	  else
	    {
	      root = NSMaxRange(range);	// ~/... or ~name/...
	    }
	}
      else
	{
	  if (pathSepMember(c))
	    {
	      root++;
	    }
	  if (GSPathHandlingUnix() == NO)
	    {
	      if (root == 0 && l > 1
		&& ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))
		&& [s characterAtIndex: 1] == ':')
		{
		  // Got a drive relative path ... see if it's absolute.
		  root = 2;
		  if (l > 2 && pathSepMember([s characterAtIndex: 2]))
		    {
		      root++;
		    }
		}
	      else if (root == 1
		&& l > 4 && pathSepMember([s characterAtIndex: 1]))
		{
		  NSRange	range = NSMakeRange(2, l-2);

		  range = [s rangeOfCharacterFromSet: pathSeps()
					     options: NSLiteralSearch
					       range: range];
		  if (range.length > 0 && range.location > 2)
		    {
		      unsigned pos = NSMaxRange(range);

		      // Found end of UNC host perhaps ... look for share
		      if (pos < l)
			{
			  range = NSMakeRange(pos, l - pos);
			  range = [s rangeOfCharacterFromSet: pathSeps()
						     options: NSLiteralSearch
						       range: range];
			  if (range.length > 0)
			    {
			      /*
			       * Found another slash ...  but if it comes
			       * immediately after the last one this can't
			       * be a UNC path as it's '//host//' rather
			       * than '//host/share'
			       */
			      if (range.location > pos)
				{
				  /* OK ... we have the '//host/share/'
				   * format, so this is a valid UNC path.
				   */
				  root = NSMaxRange(range);
				}
			    }
			}
		    }
		}
	    }
	}
    }
  return root;
}


@implementation NSString
//  NSString itself is an abstract class which provides factory
//  methods to generate objects of unspecified subclasses.

static NSStringEncoding _DefaultStringEncoding;
static BOOL		_ByteEncodingOk;
static const unichar byteOrderMark = 0xFEFF;
static const unichar byteOrderMarkSwapped = 0xFFFE;

#ifdef HAVE_REGISTER_PRINTF_FUNCTION
#include <stdio.h>
#include <printf.h>

/* <sattler@volker.cs.Uni-Magdeburg.DE>, with libc-5.3.9 thinks this
   flag PRINTF_ATSIGN_VA_LIST should be 0, but for me, with libc-5.0.9,
   it crashes.  -mccallum

   Apparently GNU libc 2.xx needs this to be 0 also, along with Linux
   libc versions 5.2.xx and higher (including libc6, which is just GNU
   libc). -chung */
#if defined(_LINUX_C_LIB_VERSION_MINOR)	\
  && _LINUX_C_LIB_VERSION_MAJOR <= 5	\
  && _LINUX_C_LIB_VERSION_MINOR < 2
#define PRINTF_ATSIGN_VA_LIST	1
#else
#define PRINTF_ATSIGN_VA_LIST	0
#endif

#if ! PRINTF_ATSIGN_VA_LIST
static int
arginfo_func (const struct printf_info *info, size_t n, int *argtypes
#if     defined(HAVE_REGISTER_PRINTF_SPECIFIER)
, int *size
#endif
)
{
  *argtypes = PA_POINTER;
  return 1;
}
#endif /* !PRINTF_ATSIGN_VA_LIST */

static int
handle_printf_atsign (FILE *stream,
		      const struct printf_info *info,
#if PRINTF_ATSIGN_VA_LIST
		      va_list *ap_pointer)
#elif defined(_LINUX_C_LIB_VERSION_MAJOR)       \
     && _LINUX_C_LIB_VERSION_MAJOR < 6
                      const void **const args)
#else /* GNU libc needs the following. */
                      const void *const *args)
#endif
{
#if ! PRINTF_ATSIGN_VA_LIST
  const void *ptr = *args;
#endif
  id string_object;
  int len;

  /* xxx This implementation may not pay pay attention to as much
     of printf_info as it should. */

#if PRINTF_ATSIGN_VA_LIST
  string_object = va_arg (*ap_pointer, id);
#else
  string_object = *((id*) ptr);
#endif
  string_object = [string_object description];

#if HAVE_WIDE_PRINTF_FUNCTION
  if (info->wide)
    {
      if (sizeof(wchar_t) == 4)
        {
	  unsigned	length = [string_object length];
	  wchar_t	buf[length + 1];
	  unsigned	i;

	  for (i = 0; i < length; i++)
	    {
	      buf[i] = [string_object characterAtIndex: i];
	    }
	  buf[i] = 0;
          len = fwprintf(stream, L"%*ls",
	    (info->left ? - info->width : info->width), buf);
        }
      else
        {
          len = fwprintf(stream, L"%*ls",
	    (info->left ? - info->width : info->width),
	    [string_object cStringUsingEncoding: NSUnicodeStringEncoding]);
	}
    }
  else
#endif	/* HAVE_WIDE_PRINTF_FUNCTION */
    {
      len = fprintf(stream, "%*s",
	(info->left ? - info->width : info->width),
	[string_object lossyCString]);
    }
  return len;
}
#endif /* HAVE_REGISTER_PRINTF_FUNCTION */

static void
register_printf_atsign ()
{
#if     defined(HAVE_REGISTER_PRINTF_SPECIFIER)
      if (register_printf_specifier ('@', handle_printf_atsign,
#if PRINTF_ATSIGN_VA_LIST
				    0))
#else
	                            arginfo_func))
#endif
	[NSException raise: NSGenericException
		     format: @"register printf handling of %%@ failed"];
#elif   defined(HAVE_REGISTER_PRINTF_FUNCTION)
      if (register_printf_function ('@', handle_printf_atsign,
#if PRINTF_ATSIGN_VA_LIST
				    0))
#else
	                            arginfo_func))
#endif
	[NSException raise: NSGenericException
		     format: @"register printf handling of %%@ failed"];
#endif
}


#if GS_USE_ICU == 1
/**
 * Returns an ICU collator for the given locale and options, or returns
 * NULL if a collator couldn't be created or the GNUstep comparison code
 * should be used instead.
 */
static UCollator *
GSICUCollatorOpen(NSStringCompareOptions mask, NSLocale *locale)
{
  UErrorCode status = U_ZERO_ERROR;
  const char *localeCString;
  UCollator *coll;
  
  if (mask & NSLiteralSearch)
    {
      return NULL;
    }

  if (NO == [locale isKindOfClass: [NSLocale class]])
    {
      if (nil == locale)
        {
          /* See comments below about the posix locale.
           * It's bad for case insensitive search, but needed for numeric
           */
          if (mask & NSNumericSearch)
            {
              locale = [NSLocale systemLocale];
            }
          else
            {
              /* A nil locale should trigger POSIX collation (i.e. 'A'-'Z' sort
               * before 'a'), and support for this was added in ICU 4.6 under the
               * locale name en_US_POSIX, but it doesn't fit our requirements
               * (e.g. 'e' and 'E' don't compare as equal with case insensitive
               * comparison.) - so return NULL to indicate that the GNUstep
               * comparison code should be used.
               */
              return NULL;
            }
        }
      else
        {
          locale = [NSLocale currentLocale];
        }
    }

  localeCString = [[locale localeIdentifier] UTF8String];

  if (localeCString != NULL && strcmp("", localeCString) == 0)
    {
      localeCString = NULL;
    }

  coll = ucol_open(localeCString, &status);

  if (U_SUCCESS(status))
    {
      if (mask & (NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch))
	{
	  ucol_setStrength(coll, UCOL_PRIMARY);
	}
      else if (mask & NSCaseInsensitiveSearch)
	{
	  ucol_setStrength(coll, UCOL_SECONDARY);
	}
      else if (mask & NSDiacriticInsensitiveSearch)
	{
	  ucol_setStrength(coll, UCOL_PRIMARY);
	  ucol_setAttribute(coll, UCOL_CASE_LEVEL, UCOL_ON, &status);
	}
      
      if (mask & NSNumericSearch)
	{
	  ucol_setAttribute(coll, UCOL_NUMERIC_COLLATION, UCOL_ON, &status);
	}
	  
      if (U_SUCCESS(status))
	{
	  return coll;
	}
    }

  ucol_close(coll);
  return NULL;
}

#if defined(HAVE_UNICODE_UNORM2_H)
- (NSString *) _normalizedICUStringOfType: (const char*)normalization
                                     mode: (UNormalization2Mode)mode
{
  UErrorCode            err;
  const UNormalizer2    *normalizer;
  int32_t               length;
  int32_t               newLength;
  NSString              *newString;

  length = (uint32_t)[self length];
  if (0 == length)
    {
      return @"";       // Simple case ... empty string
    }

  err = 0;
  normalizer = unorm2_getInstance(NULL, normalization, mode, &err);
  if (U_FAILURE(err))
    {
      [NSException raise: NSCharacterConversionException
                  format: @"libicu unorm2_getInstance() failed"];
    }

  if (length < 200)
    {
      unichar   src[length];
      unichar   dst[length*3];

      /* For a short string, it's very efficient to just use on-stack
       * buffers for the libicu work, and then let the standard string
       * initialiser convert that to an inline string.
       */
      [self getCharacters: (unichar *)src range: NSMakeRange(0, length)];
      err = 0;
      newLength = unorm2_normalize(normalizer, (UChar*)src, length,
        (UChar*)dst, length*3, &err);
      if (U_FAILURE(err))
        {
          [NSException raise: NSCharacterConversionException
                      format: @"precompose/decompose failed"];
        }
      newString = [[NSString alloc] initWithCharacters: dst length: newLength];
    }
  else
    {
      unichar   *src;
      unichar   *dst;

      /* For longer strings, we copy the source into a buffer on the heap
       * for the libicu operation, determine the length needed for the
       * output buffer, then do the actual conversion to build the string.
       */
      src = (unichar*)malloc(length * sizeof(unichar));
      [self getCharacters: (unichar*)src range: NSMakeRange(0, length)];
      err = 0;
      newLength = unorm2_normalize(normalizer, (UChar*)src, length,
        0, 0, &err);
      if (U_BUFFER_OVERFLOW_ERROR != err)
        {
          free(src);
          [NSException raise: NSCharacterConversionException
                      format: @"precompose/decompose length check failed"];
        }
      dst = NSZoneMalloc(NSDefaultMallocZone(), newLength * sizeof(unichar));
      err = 0;
      unorm2_normalize(normalizer, (UChar*)src, length,
        (UChar*)dst, newLength, &err);
      free(src);
      if (U_FAILURE(err))
        {
          NSZoneFree(NSDefaultMallocZone(), dst);
          [NSException raise: NSCharacterConversionException
                      format: @"precompose/decompose failed"];
        }
      newString = [[NSString alloc] initWithCharactersNoCopy: dst
                                                      length: newLength
                                                freeWhenDone: YES];
    }

  return AUTORELEASE(newString);
}
#endif
#endif

+ (void) atExit
{
  DESTROY(placeholderMap);
}

+ (void) initialize
{
  /*
   * Flag required as we call this method explicitly from GSBuildStrings()
   * to ensure that NSString is initialised properly.
   */
  static BOOL	beenHere = NO;

  if (self == [NSString class] && beenHere == NO)
    {
      beenHere = YES;
      cMemberSel = @selector(characterIsMember:);
      caiSel = @selector(characterAtIndex:);
      gcrSel = @selector(getCharacters:range:);
      ranSel = @selector(rangeOfComposedCharacterSequenceAtIndex:);

      nonBase = [NSCharacterSet nonBaseCharacterSet];
      nonBase = [NSObject leakAt: &nonBase];
      nonBaseImp
        = (BOOL(*)(id,SEL,unichar))[nonBase methodForSelector: cMemberSel];

      _DefaultStringEncoding = GSPrivateDefaultCStringEncoding();
      _ByteEncodingOk = GSPrivateIsByteEncoding(_DefaultStringEncoding);

      NSStringClass = self;
      [self setVersion: 1];
      NSMutableStringClass = [NSMutableString class];
      NSDataClass = [NSData class];
      GSPlaceholderStringClass = [GSPlaceholderString class];
      GSStringClass = [GSString class];
      GSMutableStringClass = [GSMutableString class];

      /*
       * Set up infrastructure for placeholder strings.
       */
      defaultPlaceholderString = (GSPlaceholderString*)
	[GSPlaceholderStringClass allocWithZone: NSDefaultMallocZone()];
      placeholderMap = NSCreateMapTable(NSNonOwnedPointerMapKeyCallBacks,
	NSNonRetainedObjectMapValueCallBacks, 0);
      register_printf_atsign();
      [self registerAtExit];
    }
}

+ (id) allocWithZone: (NSZone*)z
{
  if (self == NSStringClass)
    {
      /*
       * For a constant string, we return a placeholder object that can
       * be converted to a real object when its initialisation method
       * is called.
       */
      if (z == NSDefaultMallocZone() || z == 0)
	{
	  /*
	   * As a special case, we can return a placeholder for a string
	   * in the default zone extremely efficiently.
	   */
	  return defaultPlaceholderString;
	}
      else
	{
	  id	obj;

	  /*
	   * For anything other than the default zone, we need to
	   * locate the correct placeholder in the (lock protected)
	   * table of placeholders.
	   */
	  (void)pthread_mutex_lock(&placeholderLock);
	  obj = (id)NSMapGet(placeholderMap, (void*)z);
	  if (obj == nil)
	    {
	      /*
	       * There is no placeholder object for this zone, so we
	       * create a new one and use that.
	       */
	      obj = (id)[GSPlaceholderStringClass allocWithZone: z];
	      NSMapInsert(placeholderMap, (void*)z, (void*)obj);
	    }
	  (void)pthread_mutex_unlock(&placeholderLock);
	  return obj;
	}
    }
  else if ([self isKindOfClass: GSStringClass] == YES)
    {
      [NSException raise: NSInternalInconsistencyException
		  format: @"Called +allocWithZone: on private string class"];
      return nil;	/* NOT REACHED */
    }
  else
    {
      /*
       * For user provided strings, we simply allocate an object of
       * the given class.
       */
      return NSAllocateObject (self, 0, z);
    }
}

/**
 * Return the class used to store constant strings (those ascii strings
 * placed in the source code using the @"this is a string" syntax).<br />
 * Use this method to obtain the constant string class rather than
 * using the obsolete name <em>NXConstantString</em> in your code ...
 * with more recent compiler versions the name of this class is variable
 * (and will automatically be changed by GNUstep to avoid conflicts
 * with the default implementation in the Objective-C runtime library).
 */
+ (Class) constantStringClass
{
  return [@"" class];
}

/**
 * Create an empty string.
 */
+ (id) string
{
  return AUTORELEASE([[self allocWithZone: NSDefaultMallocZone()] init]);
}

/**
 * Create a copy of aString.
 */
+ (id) stringWithString: (NSString*)aString
{
  NSString	*obj;

  if (NULL == aString)
    [NSException raise: NSInvalidArgumentException
      format: @"[NSString+stringWithString:]: NULL string"];
  obj = [self allocWithZone: NSDefaultMallocZone()];
  obj = [obj initWithString: aString];
  return AUTORELEASE(obj);
}

/**
 * Create a string of unicode characters.
 */
+ (id) stringWithCharacters: (const unichar*)chars
		     length: (NSUInteger)length
{
  NSString	*obj;

  obj = [self allocWithZone: NSDefaultMallocZone()];
  obj = [obj initWithCharacters: chars length: length];
  return AUTORELEASE(obj);
}

/**
 * Create a string based on the given C (char[]) string, which should be
 * null-terminated and encoded in the default C string encoding.  (Characters
 * will be converted to unicode representation internally.)
 */
+ (id) stringWithCString: (const char*)byteString
{
  NSString	*obj;

  if (NULL == byteString)
    [NSException raise: NSInvalidArgumentException
      format: @"[NSString+stringWithCString:]: NULL cString"];
  obj = [self allocWithZone: NSDefaultMallocZone()];
  obj = [obj initWithCString: byteString];
  return AUTORELEASE(obj);
}

/**
 * Create a string based on the given C (char[]) string, which should be
 * null-terminated and encoded in the specified C string encoding.
 * Characters may be converted to unicode representation internally.
 */
+ (id) stringWithCString: (const char*)byteString
		encoding: (NSStringEncoding)encoding
{
  NSString	*obj;

  if (NULL == byteString)
    [NSException raise: NSInvalidArgumentException
      format: @"[NSString+stringWithCString:encoding:]: NULL cString"];
  obj = [self allocWithZone: NSDefaultMallocZone()];
  obj = [obj initWithCString: byteString encoding: encoding];
  return AUTORELEASE(obj);
}

/**
 * Create a string based on the given C (char[]) string, which may contain
 * null bytes and should be encoded in the default C string encoding.
 * (Characters will be converted to unicode representation internally.)
 */
+ (id) stringWithCString: (const char*)byteString
		  length: (NSUInteger)length
{
  NSString	*obj;

  obj = [self allocWithZone: NSDefaultMallocZone()];
  obj = [obj initWithCString: byteString length: length];
  return AUTORELEASE(obj);
}

/**
 * Create a string based on the given UTF-8 string, null-terminated.<br />
 * Raises NSInvalidArgumentException if given NULL pointer.
 */
+ (id) stringWithUTF8String: (const char *)bytes
{
  NSString	*obj;

  if (NULL == bytes)
    [NSException raise: NSInvalidArgumentException
		format: @"[NSString+stringWithUTF8String:]: NULL cString"];
  if (self == NSStringClass)
    {
      obj = defaultPlaceholderString;
    }
  else
    {
      obj = [self allocWithZone: NSDefaultMallocZone()];
    }
  obj = [obj initWithUTF8String: bytes];
  return AUTORELEASE(obj);
}

/**
 * Load contents of file at path into a new string.  Will interpret file as
 * containing direct unicode if it begins with the unicode byte order mark,
 * else converts to unicode using default C string encoding.
 */
+ (id) stringWithContentsOfFile: (NSString *)path
{
  NSString	*obj;

  obj = [self allocWithZone: NSDefaultMallocZone()];
  obj = [obj initWithContentsOfFile: path];
  return AUTORELEASE(obj);
}

/**
 * Load contents of file at path into a new string using the
 * -initWithContentsOfFile:usedEncoding:error: method.
 */
+ (id) stringWithContentsOfFile: (NSString *)path
                   usedEncoding: (NSStringEncoding*)enc
                          error: (NSError**)error
{
  NSString	*obj;

  obj = [self allocWithZone: NSDefaultMallocZone()];
  obj = [obj initWithContentsOfFile: path usedEncoding: enc error: error];
  return AUTORELEASE(obj);
}

/**
 * Load contents of file at path into a new string using the
 * -initWithContentsOfFile:encoding:error: method.
 */
+ (id) stringWithContentsOfFile: (NSString*)path
                       encoding: (NSStringEncoding)enc
                          error: (NSError**)error
{
   NSString	*obj;

  obj = [self allocWithZone: NSDefaultMallocZone()];
  obj = [obj initWithContentsOfFile: path encoding: enc error: error];
  return AUTORELEASE(obj);
}

/**
 * Load contents of given URL into a new string.  Will interpret contents as
 * containing direct unicode if it begins with the unicode byte order mark,
 * else converts to unicode using default C string encoding.
 */
+ (id) stringWithContentsOfURL: (NSURL *)url
{
  NSString	*obj;

  obj = [self allocWithZone: NSDefaultMallocZone()];
  obj = [obj initWithContentsOfURL: url];
  return AUTORELEASE(obj);
}

+ (id) stringWithContentsOfURL: (NSURL*)url
                  usedEncoding: (NSStringEncoding*)enc
                         error: (NSError**)error
{
  NSString	*obj;

  obj = [self allocWithZone: NSDefaultMallocZone()];
  obj = [obj initWithContentsOfURL: url usedEncoding: enc error: error];
  return AUTORELEASE(obj);
}

+ (id) stringWithContentsOfURL: (NSURL*)url
                      encoding: (NSStringEncoding)enc
                         error: (NSError**)error
{
  NSString	*obj;

  obj = [self allocWithZone: NSDefaultMallocZone()];
  obj = [obj initWithContentsOfURL: url encoding: enc error: error];
  return AUTORELEASE(obj);
}

/**
 * Creates a new string using C printf-style formatting.  First argument should
 * be a constant format string, like '<code>@"float val = %f"</code>', remaining
 * arguments should be the variables to print the values of, comma-separated.
 */
+ (id) stringWithFormat: (NSString*)format,...
{
  va_list ap;
  NSString	*obj;

  if (NULL == format)
    [NSException raise: NSInvalidArgumentException
      format: @"[NSString+stringWithFormat:]: NULL format"];
  va_start(ap, format);
  obj = [self allocWithZone: NSDefaultMallocZone()];
  obj = [obj initWithFormat: format arguments: ap];
  va_end(ap);
  return AUTORELEASE(obj);
}


/**
 * <p>In MacOS-X class clusters do not have designated initialisers,
 * and there is a general rule that -init is treated as the designated
 * initialiser of the class cluster, but that other intitialisers
 * may not work as expected and would need to be individually overridden
 * in any subclass.
 * </p>
 * <p>GNUstep tries to make it easier to subclass a class cluster,
 * by making class clusters follow the same convention as normal
 * classes, so the designated initialiser is the <em>richest</em>
 * initialiser.  This means that all other initialisers call the
 * documented designated initialiser (which calls -init only for
 * MacOS-X compatibility), and anyone writing a subclass only needs
 * to override that one initialiser in order to have all the other
 * ones work.
 * </p>
 * <p>For MacOS-X compatibility, you may also need to override various
 * other initialisers.  Exactly which ones, you will need to determine
 * by trial on a MacOS-X system ... and may vary between releases of
 * MacOS-X.  So to be safe, on MacOS-X you probably need to re-implement
 * <em>all</em> the class cluster initialisers you might use in conjunction
 * with your subclass.
 * </p>
 * <p>NB. The GNUstep designated initialiser for the NSString class cluster
 * has changed to -initWithBytesNoCopy:length:encoding:freeWhenDone:
 * from -initWithCharactersNoCopy:length:freeWhenDone: and older code
 * subclassing NSString will need to be updated.
 * </p>
 */
- (id) init
{
  self = [super init];
  return self;
}

/**
 * Initialises the receiver with a copy of the supplied length of bytes,
 * using the specified encoding.<br />
 * For NSUnicodeStringEncoding and NSUTF8String encoding, a Byte Order
 * Marker (if present at the start of the data) is removed automatically.<br />
 * If the data can not be interpreted using the encoding, the receiver
 * is released and nil is returned.
 */
- (id) initWithBytes: (const void*)bytes
	      length: (NSUInteger)length
	    encoding: (NSStringEncoding)encoding
{
  if (length == 0)
    {
      return [self initWithBytesNoCopy: (void *)0
				length: 0
			      encoding: encoding
			  freeWhenDone: NO];
    }
  else
    {
      void	*buf;

      buf = NSZoneMalloc([self zone], length);
      memcpy(buf, bytes, length);
      return [self initWithBytesNoCopy: buf
				length: length
			      encoding: encoding
			  freeWhenDone: YES];
    }
}

/** <init /> <override-subclass />
 * Initialises the receiver with the supplied length of bytes, using the
 * specified encoding.<br />
 * For NSUnicodeStringEncoding and NSUTF8String encoding, a Byte Order
 * Marker (if present at the start of the data) is removed automatically.<br />
 * If the data is not in a format which can be used internally unmodified,
 * it is copied, otherwise it is used as is.  If the data is not copied
 * the flag determines whether the string will free it when it is no longer
 * needed (ie whether the new NSString instance 'owns' the memory).<br />
 * In the case of non-owned memory, it is the caller's responsibility to
 * ensure that the data continues to exist and is not modified until the
 * receiver is deallocated.<br />
 * If the data can not be interpreted using the encoding, the receiver
 * is released and nil is returned.
 * <p>Note, this is the most basic initialiser for strings.
 * In the GNUstep implementation, your subclasses may override
 * this initialiser in order to have all other functionality.</p>
 */
- (id) initWithBytesNoCopy: (void*)bytes
		    length: (NSUInteger)length
		  encoding: (NSStringEncoding)encoding
	      freeWhenDone: (BOOL)flag
{
  self = [self init];
  return self;
}

/**
 * <p>Initialize with given unicode chars up to length, regardless of presence
 *  of null bytes.  Does not copy the string.  If flag, frees its storage when
 *  this instance is deallocated.</p>
 * See -initWithBytesNoCopy:length:encoding:freeWhenDone: for more details.
 */
- (id) initWithCharactersNoCopy: (unichar*)chars
			 length: (NSUInteger)length
		   freeWhenDone: (BOOL)flag
{
  return [self initWithBytesNoCopy: chars
			    length: length * sizeof(unichar)
			  encoding: NSUnicodeStringEncoding
		      freeWhenDone: flag];
}

/**
 * <p>Initialize with given unicode chars up to length, regardless of presence
 *  of null bytes.  Copies the string and frees copy when deallocated.</p>
 */
- (id) initWithCharacters: (const unichar*)chars
		   length: (NSUInteger)length
{
  return [self initWithBytes: chars
		      length: length * sizeof(unichar)
		    encoding: NSUnicodeStringEncoding];
}

/**
 * <p>Initialize with given C string byteString up to length, regardless of
 *  presence of null bytes.  Characters converted to unicode based on the
 *  default C encoding.  Does not copy the string.  If flag, frees its storage
 *  when this instance is deallocated.</p>
 * See -initWithBytesNoCopy:length:encoding:freeWhenDone: for more details.
 */
- (id) initWithCStringNoCopy: (char*)byteString
		      length: (NSUInteger)length
		freeWhenDone: (BOOL)flag
{
  return [self initWithBytesNoCopy: byteString
			    length: length
			  encoding: _DefaultStringEncoding
		      freeWhenDone: flag];
}

/**
 * <p>Initialize with given C string byteString up to first nul byte.
 * Characters converted to unicode based on the specified C encoding.
 * Copies the string.</p>
 */
- (id) initWithCString: (const char*)byteString
	      encoding: (NSStringEncoding)encoding
{
  if (NULL == byteString)
    [NSException raise: NSInvalidArgumentException
      format: @"[NSString-initWithCString:encoding:]: NULL cString"];
  return [self initWithBytes: byteString
		      length: strlen(byteString)
		    encoding: encoding];
}

/**
 * <p>Initialize with given C string byteString up to length, regardless of
 *  presence of null bytes.  Characters converted to unicode based on the
 *  default C encoding.  Copies the string.</p>
 */
- (id) initWithCString: (const char*)byteString  length: (NSUInteger)length
{
  return [self initWithBytes: byteString
		      length: length
		    encoding: _DefaultStringEncoding];
}

/**
 * <p>Initialize with given C string byteString, which should be
 * null-terminated.  Characters are converted to unicode based on the default
 * C encoding.  Copies the string.</p>
 */
- (id) initWithCString: (const char*)byteString
{
  if (NULL == byteString)
    [NSException raise: NSInvalidArgumentException
      format: @"[NSString-initWithCString:]: NULL cString"];
  return [self initWithBytes: byteString
		      length: strlen(byteString)
		    encoding: _DefaultStringEncoding];
}

/**
 * Initialize to be a copy of the given string.
 */
- (id) initWithString: (NSString*)string
{
  unsigned	length = [string length];

  if (NULL == string)
    [NSException raise: NSInvalidArgumentException
      format: @"[NSString-initWithString:]: NULL string"];
  if (length > 0)
    {
      unichar	*s = NSZoneMalloc([self zone], sizeof(unichar)*length);

      [string getCharacters: s range: ((NSRange){0, length})];
      self = [self initWithCharactersNoCopy: s
				     length: length
			       freeWhenDone: YES];
    }
  else
    {
      self = [self initWithCharactersNoCopy: (unichar*)0
				     length: 0
			       freeWhenDone: NO];
    }
  return self;
}

/**
 * Initialize based on given null-terminated UTF-8 string bytes.
 */
- (id) initWithUTF8String: (const char *)bytes
{
  if (NULL == bytes)
    [NSException raise: NSInvalidArgumentException
		format: @"[NSString-initWithUTF8String:]: NULL cString"];
  return [self initWithBytes: bytes
		      length: strlen(bytes)
		    encoding: NSUTF8StringEncoding];
}

/**
 * Invokes -initWithFormat:locale:arguments: with a nil locale.
 */
- (id) initWithFormat: (NSString*)format,...
{
  va_list ap;
  va_start(ap, format);
  self = [self initWithFormat: format locale: nil arguments: ap];
  va_end(ap);
  return self;
}

/**
 * Invokes -initWithFormat:locale:arguments:
 */
- (id) initWithFormat: (NSString*)format
               locale: (NSDictionary*)locale, ...
{
  va_list ap;
  va_start(ap, locale);
  self = [self initWithFormat: format locale: locale arguments: ap];
  va_end(ap);
  return self;
}

/**
 * Invokes -initWithFormat:locale:arguments: with a nil locale.
 */
- (id) initWithFormat: (NSString*)format
            arguments: (va_list)argList
{
  return [self initWithFormat: format locale: nil arguments: argList];
}

/**
 * Initialises the string using the specified format and locale
 * to format the following arguments.
 */
- (id) initWithFormat: (NSString*)format
               locale: (NSDictionary*)locale
            arguments: (va_list)argList
{
  unsigned char	buf[2048];
  GSStr		f;
  unichar	fbuf[1024];
  unichar	*fmt = fbuf;
  size_t	len;

  if (NULL == format)
    [NSException raise: NSInvalidArgumentException
      format: @"[NSString-initWithFormat:locale:arguments:]: NULL format"];
  /*
   * First we provide an array of unichar characters containing the
   * format string.  For performance reasons we try to use an on-stack
   * buffer if the format string is small enough ... it almost always
   * will be.
   */
  len = [format length];
  if (len >= 1024)
    {
      fmt = NSZoneMalloc(NSDefaultMallocZone(), (len+1)*sizeof(unichar));
    }
  [format getCharacters: fmt range: ((NSRange){0, len})];
  fmt[len] = '\0';

  /*
   * Now set up 'f' as a GSMutableString object whose initial buffer is
   * allocated on the stack.  The GSPrivateFormat function can write into it.
   */
  f = (GSStr)alloca(class_getInstanceSize(GSMutableStringClass));
  object_setClass(f, GSMutableStringClass);
  f->_zone = NSDefaultMallocZone();
  f->_contents.c = buf;
  f->_capacity = sizeof(buf);
  f->_count = 0;
  f->_flags.wide = 0;
  f->_flags.owned = 0;
  f->_flags.unused = 0;
  f->_flags.hash = 0;
  GSPrivateFormat(f, fmt, argList, locale);
  GSPrivateStrExternalize(f);
  if (fmt != fbuf)
    {
      NSZoneFree(NSDefaultMallocZone(), fmt);
    }

  /*
   * Don't use noCopy because f->_contents.u may be memory on the stack,
   * and even if it wasn't f->_capacity may be greater than f->_count so
   * we could be wasting quite a bit of space.  Better to accept a
   * performance hit due to copying data (and allocating/deallocating
   * the temporary buffer) for large strings.  For most strings, the
   * on-stack memory will have been used, so we will get better performance.
   */
  if (f->_flags.wide == 1)
    {
      self = [self initWithCharacters: f->_contents.u length: f->_count];
    }
  else
    {
      self = [self initWithCString: (char*)f->_contents.c length: f->_count];
    }

  /*
   * If the string had to grow beyond the initial buffer size, we must
   * release any allocated memory.
   */
  if (f->_flags.owned == 1)
    {
      NSZoneFree(f->_zone, f->_contents.c);
    }
  return self;
}

/**
 * Initialises the receiver with the supplied data, using the
 * specified encoding.<br />
 * For NSUnicodeStringEncoding and NSUTF8String encoding, a Byte Order
 * Marker (if present at the start of the data) is removed automatically.<br />
 * If the data can not be interpreted using the encoding, the receiver
 * is released and nil is returned.
 */
- (id) initWithData: (NSData*)data
	   encoding: (NSStringEncoding)encoding
{
  return [self initWithBytes: [data bytes]
		      length: [data length]
		    encoding: encoding];
}

/**
 * <p>Initialises the receiver with the contents of the file at path.
 * </p>
 * <p>Invokes [NSData-initWithContentsOfFile:] to read the file, then
 * examines the data to infer its encoding type, and converts the
 * data to a string using -initWithData:encoding:
 * </p>
 * <p>The encoding to use is determined as follows ... if the data begins
 * with the 16-bit unicode Byte Order Marker, then it is assumed to be
 * unicode data in the appropriate ordering and converted as such.<br />
 * If it begins with a UTF8 representation of the BOM, the UTF8 encoding
 * is used.<br />
 * Otherwise, the default C String encoding is used.
 * </p>
 * <p>Releases the receiver and returns nil if the file could not be read
 * and converted to a string.
 * </p>
 */
- (id) initWithContentsOfFile: (NSString*)path
{
  NSStringEncoding	enc = _DefaultStringEncoding;
  NSData		*d;
  unsigned int		len;
  const unsigned char	*data_bytes;

  d = [[NSDataClass alloc] initWithContentsOfFile: path];
  if (d == nil)
    {
      DESTROY(self);
      return nil;
    }
  len = [d length];
  if (len == 0)
    {
      RELEASE(d);
      DESTROY(self);
      return @"";
    }
  data_bytes = [d bytes];
  if ((data_bytes != NULL) && (len >= 2))
    {
      const unichar *data_ucs2chars = (const unichar *)(void*) data_bytes;
      if ((data_ucs2chars[0] == byteOrderMark)
	|| (data_ucs2chars[0] == byteOrderMarkSwapped))
	{
	  /* somebody set up us the BOM! */
	  enc = NSUnicodeStringEncoding;
	}
      else if (len >= 3
	&& data_bytes[0] == 0xEF
	&& data_bytes[1] == 0xBB
	&& data_bytes[2] == 0xBF)
	{
	  enc = NSUTF8StringEncoding;
	}
    }
  self = [self initWithData: d encoding: enc];
  RELEASE(d);
  if (self == nil)
    {
      NSWarnMLog(@"Contents of file '%@' are not string data using %@",
        path, [NSString localizedNameOfStringEncoding: enc]);
    }
  return self;
}

/**
 * <p>Initialises the receiver with the contents of the file at path.
 * </p>
 * <p>Invokes [NSData-initWithContentsOfFile:] to read the file, then
 * examines the data to infer its encoding type, and converts the
 * data to a string using -initWithData:encoding:
 * </p>
 * <p>The encoding to use is determined as follows ... if the data begins
 * with the 16-bit unicode Byte Order Marker, then it is assumed to be
 * unicode data in the appropriate ordering and converted as such.<br />
 * If it begins with a UTF8 representation of the BOM, the UTF8 encoding
 * is used.<br />
 * Otherwise, the default C String encoding is used.
 * </p>
 * <p>Releases the receiver and returns nil if the file could not be read
 * and converted to a string.
 * </p>
 */
- (id) initWithContentsOfFile: (NSString*)path
                 usedEncoding: (NSStringEncoding*)enc
                        error: (NSError**)error
{
  NSData		*d;
  unsigned int		len;
  const unsigned char	*data_bytes;

  d = [[NSDataClass alloc] initWithContentsOfFile: path];
  if (nil == d)
    {
      DESTROY(self);
      if (error != 0)
        {
          *error = [NSError errorWithDomain: NSCocoaErrorDomain
                                       code: NSFileReadUnknownError
                                   userInfo: nil];
        }
      return nil;
    }
  *enc = _DefaultStringEncoding;
  len = [d length];
  if (len == 0)
    {
      RELEASE(d);
      DESTROY(self);
      return @"";
    }
  data_bytes = [d bytes];
  if ((data_bytes != NULL) && (len >= 2))
    {
      const unichar *data_ucs2chars = (const unichar *)(void*) data_bytes;
      if ((data_ucs2chars[0] == byteOrderMark)
	|| (data_ucs2chars[0] == byteOrderMarkSwapped))
	{
	  /* somebody set up us the BOM! */
	  *enc = NSUnicodeStringEncoding;
	}
      else if (len >= 3
	&& data_bytes[0] == 0xEF
	&& data_bytes[1] == 0xBB
	&& data_bytes[2] == 0xBF)
	{
	  *enc = NSUTF8StringEncoding;
	}
    }
  self = [self initWithData: d encoding: *enc];
  RELEASE(d);
  if (nil == self)
    {
      if (error != 0)
        {
          *error = [NSError errorWithDomain: NSCocoaErrorDomain
                                       code: NSFileReadCorruptFileError
                                   userInfo: nil];
        }
    }
  return self;
}

- (id) initWithContentsOfFile: (NSString*)path
                     encoding: (NSStringEncoding)enc
                        error: (NSError**)error
{
  NSData		*d;
  unsigned int		len;

  d = [[NSDataClass alloc] initWithContentsOfFile: path];
  if (d == nil)
    {
      DESTROY(self);
      return nil;
    }
  len = [d length];
  if (len == 0)
    {
      RELEASE(d);
      DESTROY(self);
      return @"";
    }
  self = [self initWithData: d encoding: enc];
  RELEASE(d);
  if (self == nil)
    {
      if (error != 0)
        {
          *error = [NSError errorWithDomain: NSCocoaErrorDomain
                                       code: NSFileReadCorruptFileError
                                   userInfo: nil];
        }
    }
  return self;
}

/**
 * <p>Initialises the receiver with the contents of the given URL.
 * </p>
 * <p>Invokes [NSData+dataWithContentsOfURL:] to read the contents, then
 * examines the data to infer its encoding type, and converts the
 * data to a string using -initWithData:encoding:
 * </p>
 * <p>The encoding to use is determined as follows ... if the data begins
 * with the 16-bit unicode Byte Order Marker, then it is assumed to be
 * unicode data in the appropriate ordering and converted as such.<br />
 * If it begins with a UTF8 representation of the BOM, the UTF8 encoding
 * is used.<br />
 * Otherwise, the default C String encoding is used.
 * </p>
 * <p>Releases the receiver and returns nil if the URL contents could not be
 * read and converted to a string.
 * </p>
 */
- (id) initWithContentsOfURL: (NSURL*)url
{
  NSStringEncoding	enc = _DefaultStringEncoding;
  NSData		*d = [NSDataClass dataWithContentsOfURL: url];
  unsigned int		len = [d length];
  const unsigned char	*data_bytes;

  if (d == nil)
    {
      NSWarnMLog(@"Contents of URL '%@' are not readable", url);
      DESTROY(self);
      return nil;
    }
  if (len == 0)
    {
      DESTROY(self);
      return @"";
    }
  data_bytes = [d bytes];
  if ((data_bytes != NULL) && (len >= 2))
    {
      const unichar *data_ucs2chars = (const unichar *)(void*) data_bytes;
      if ((data_ucs2chars[0] == byteOrderMark)
	|| (data_ucs2chars[0] == byteOrderMarkSwapped))
	{
	  enc = NSUnicodeStringEncoding;
	}
      else if (len >= 3
	&& data_bytes[0] == 0xEF
	&& data_bytes[1] == 0xBB
	&& data_bytes[2] == 0xBF)
	{
	  enc = NSUTF8StringEncoding;
	}
    }
  self = [self initWithData: d encoding: enc];
  if (self == nil)
    {
      NSWarnMLog(@"Contents of URL '%@' are not string data using %@",
        url, [NSString localizedNameOfStringEncoding: enc]);
    }
  return self;
}

- (id) initWithContentsOfURL: (NSURL*)url
                usedEncoding: (NSStringEncoding*)enc
                       error: (NSError**)error
{
  NSData		*d;
  unsigned int		len;
  const unsigned char	*data_bytes;

  d = [NSDataClass dataWithContentsOfURL: url];
  if (d == nil)
    {
      DESTROY(self);
      return nil;
    }
  *enc = _DefaultStringEncoding;
  len = [d length];
  if (len == 0)
    {
      DESTROY(self);
      return @"";
    }
  data_bytes = [d bytes];
  if ((data_bytes != NULL) && (len >= 2))
    {
      const unichar *data_ucs2chars = (const unichar *)(void*) data_bytes;
      if ((data_ucs2chars[0] == byteOrderMark)
	|| (data_ucs2chars[0] == byteOrderMarkSwapped))
	{
	  /* somebody set up us the BOM! */
	  *enc = NSUnicodeStringEncoding;
	}
      else if (len >= 3
	&& data_bytes[0] == 0xEF
	&& data_bytes[1] == 0xBB
	&& data_bytes[2] == 0xBF)
	{
	  *enc = NSUTF8StringEncoding;
	}
    }
  self = [self initWithData: d encoding: *enc];
  if (self == nil)
    {
      if (error != 0)
        {
          *error = [NSError errorWithDomain: NSCocoaErrorDomain
                                       code: NSFileReadCorruptFileError
                                   userInfo: nil];
        }
    }
  return self;
}

- (id) initWithContentsOfURL: (NSURL*)url
                    encoding: (NSStringEncoding)enc
                       error: (NSError**)error
{
  NSData		*d;
  unsigned int		len;

  d = [NSDataClass dataWithContentsOfURL: url];
  if (d == nil)
    {
      DESTROY(self);
      return nil;
    }
  len = [d length];
  if (len == 0)
    {
      DESTROY(self);
      return @"";
    }
  self = [self initWithData: d encoding: enc];
  if (self == nil)
    {
      if (error != 0)
        {
          *error = [NSError errorWithDomain: NSCocoaErrorDomain
                                       code: NSFileReadCorruptFileError
                                   userInfo: nil];
        }
    }
  return self;
}

/**
 * Returns the number of Unicode characters in this string, including the
 * individual characters of composed character sequences,
 */
- (NSUInteger) length
{
  [self subclassResponsibility: _cmd];
  return 0;
}

// Accessing Characters

/**
 * Returns unicode character at index.  <code>unichar</code> is an unsigned
 * short.  Thus, a 16-bit character is returned.
 */
- (unichar) characterAtIndex: (NSUInteger)index
{
  [self subclassResponsibility: _cmd];
  return (unichar)0;
}

- (NSString *) decomposedStringWithCompatibilityMapping
{
#if (GS_USE_ICU == 1) && defined(HAVE_UNICODE_UNORM2_H)
  return [self _normalizedICUStringOfType: "nfkc" mode: UNORM2_DECOMPOSE];
#else
  return [self notImplemented: _cmd];
#endif
}

- (NSString *) decomposedStringWithCanonicalMapping
{
#if (GS_USE_ICU == 1) && defined(HAVE_UNICODE_UNORM2_H)
  return [self _normalizedICUStringOfType: "nfc" mode: UNORM2_DECOMPOSE];
#else
  return [self notImplemented: _cmd];
#endif
}
 
/**
 * Returns this string as an array of 16-bit <code>unichar</code> (unsigned
 * short) values.  buffer must be preallocated and should be capable of
 * holding -length shorts.
 */
// Inefficient.  Should be overridden
- (void) getCharacters: (unichar*)buffer
{
  [self getCharacters: buffer range: ((NSRange){0, [self length]})];
  return;
}

/**
 * Returns aRange of string as an array of 16-bit <code>unichar</code>
 * (unsigned short) values.  buffer must be preallocated and should be capable
 * of holding a sufficient number of shorts.
 */
// Inefficient.  Should be overridden
- (void) getCharacters: (unichar*)buffer
		 range: (NSRange)aRange
{
  unsigned	l = [self length];
  unsigned	i;
  unichar	(*caiImp)(NSString*, SEL, NSUInteger);

  GS_RANGE_CHECK(aRange, l);

  caiImp = (unichar (*)(NSString*,SEL,NSUInteger))
    [self methodForSelector: caiSel];

  for (i = 0; i < aRange.length; i++)
    {
      buffer[i] = (*caiImp)(self, caiSel, aRange.location + i);
    }
}

- (NSString *) stringByAddingPercentEncodingWithAllowedCharacters:
  (NSCharacterSet *)aSet
{
  NSData	*data = [self dataUsingEncoding: NSUTF8StringEncoding];
  NSString	*s = nil;

  if (data != nil)
    {
      unsigned char	*src = (unsigned char*)[data bytes];
      unsigned int	slen = [data length];
      unsigned char	*dst;
      unsigned int	spos = 0;
      unsigned int	dpos = 0;

      dst = (unsigned char*)NSZoneMalloc(NSDefaultMallocZone(), slen * 3);
      while (spos < slen)
	{
	  unichar	c = src[spos++];
	  unsigned int	hi;
	  unsigned int	lo;

	  /* If the character is in the allowed set *and* is in the
	   * 7-bit ASCII range, it can be added unchanged.
	   */
	  if (c < 128 && [aSet characterIsMember: c])
	    {
	      dst[dpos++] = c;
	    }
	  else // if not, then encode it...
	    {
	      dst[dpos++] = '%';
	      hi = (c & 0xf0) >> 4;
	      dst[dpos++] = (hi > 9) ? 'A' + hi - 10 : '0' + hi;
	      lo = (c & 0x0f);
	      dst[dpos++] = (lo > 9) ? 'A' + lo - 10 : '0' + lo;
	    }
	}
      s = [[NSString alloc] initWithBytes: dst
				   length: dpos
				 encoding: NSASCIIStringEncoding];
      NSZoneFree(NSDefaultMallocZone(), dst);
      IF_NO_GC([s autorelease];)
    }
  return s;
}

- (NSString *) stringByRemovingPercentEncoding
{
  NSData	*data = [self dataUsingEncoding: NSUTF8StringEncoding];
  const uint8_t	*s = [data bytes];
  NSUInteger	length = [data length]; 
  NSUInteger	lastPercent = length - 3;
  char		*o = (char *)NSZoneMalloc(NSDefaultMallocZone(), length + 1);
  char		*next = o;
  NSUInteger	index;
  NSString	*result;

  for (index = 0; index < length; index++)
    {
      char	c = s[index];

      if ('%' == c && index <= lastPercent)
	{
	  uint8_t	hi = s[index+1];
	  uint8_t	lo = s[index+2];

	  if (isxdigit(hi) && isxdigit(lo))
	    {
	      index += 2;
              if (hi <= '9')
                {
                  c = hi - '0';
                }
              else if (hi <= 'F')
                {
                  c = hi - 'A' + 10;
                }
              else
                {
                  c = hi - 'a' + 10;
                }
	      c <<= 4;
              if (lo <= '9')
                {
                  c += lo - '0';
                }
              else if (lo <= 'F')
                {
                  c += lo - 'A' + 10;
                }
              else
                {
                  c += lo - 'a' + 10;
                }
	    }
	}
      *next++ = c;
    }
  *next = '\0';

  result = [NSString stringWithUTF8String: o];
  NSZoneFree(NSDefaultMallocZone(), o);
  
  return result; 
}

/**
 * Constructs a new ASCII string which is a representation of the receiver
 * in which characters are escaped where necessary in order to produce a
 * version of the string legal for inclusion within a URL.<br />
 * The original string is converted to bytes using the specified encoding
 * and then those bytes are escaped unless they correspond to 'legal'
 * ASCII characters.  The byte values escaped are any below 32 and any
 * above 126 as well as 32 (space), 34 ("), 35 (#), 37 (%), 60 (&lt;),
 * 62 (&gt;), 91 ([), 92 (\), 93 (]), 94 (^), 96 (~), 123 ({), 124 (|),
 * and 125 (}).<br />
 * Returns nil if the receiver cannot be represented using the specified
 * encoding.<br />
 * NB. This behavior is MacOS-X (4.2) compatible, and it should be noted
 * that it does <em>not</em> produce a string suitable for use as a field
 * value in a url-encoded form as it does <strong>not</strong> escape the
 * '+', '=' and '&amp;' characters used in such forms.  If you need to
 * add a string as a form field value (or name) you must add percent
 * escapes for those characters yourself.
 */
- (NSString*) stringByAddingPercentEscapesUsingEncoding: (NSStringEncoding)e
{
  NSData	*data = [self dataUsingEncoding: e];
  NSString	*s = nil;

  if (data != nil)
    {
      unsigned char	*src = (unsigned char*)[data bytes];
      unsigned int	slen = [data length];
      unsigned char	*dst;
      unsigned int	spos = 0;
      unsigned int	dpos = 0;

      dst = (unsigned char*)NSZoneMalloc(NSDefaultMallocZone(), slen * 3);
      while (spos < slen)
	{
	  unsigned char	c = src[spos++];
	  unsigned int	hi;
	  unsigned int	lo;

	  if (c <= 32 || c > 126 || c == 34 || c == 35 || c == 37
	    || c == 60 || c == 62 || c == 91 || c == 92 || c == 93
	    || c == 94 || c == 96 || c == 123 || c == 124 || c == 125)
	    {
	      dst[dpos++] = '%';
	      hi = (c & 0xf0) >> 4;
	      dst[dpos++] = (hi > 9) ? 'A' + hi - 10 : '0' + hi;
	      lo = (c & 0x0f);
	      dst[dpos++] = (lo > 9) ? 'A' + lo - 10 : '0' + lo;
	    }
	  else
	    {
	      dst[dpos++] = c;
	    }
	}
      s = [[NSString alloc] initWithBytes: dst
				   length: dpos
				 encoding: NSASCIIStringEncoding];
      NSZoneFree(NSDefaultMallocZone(), dst);
      IF_NO_GC([s autorelease];)
    }
  return s;
}

/**
 * Constructs a new string consisting of this instance followed by the string
 * specified by format.
 */
- (NSString*) stringByAppendingFormat: (NSString*)format,...
{
  va_list	ap;
  id		ret;

  va_start(ap, format);
  ret = [self stringByAppendingString:
    [NSString stringWithFormat: format arguments: ap]];
  va_end(ap);
  return ret;
}

/**
 * Constructs a new string consisting of this instance followed by the aString.
 */
- (NSString*) stringByAppendingString: (NSString*)aString
{
  unsigned	len = [self length];
  unsigned	otherLength = [aString length];
  NSZone	*z = [self zone];
  unichar	*s = NSZoneMalloc(z, (len+otherLength)*sizeof(unichar));
  NSString	*tmp;

  [self getCharacters: s range: ((NSRange){0, len})];
  [aString getCharacters: s + len range: ((NSRange){0, otherLength})];
  tmp = [[NSStringClass allocWithZone: z] initWithCharactersNoCopy: s
    length: len + otherLength freeWhenDone: YES];
  return AUTORELEASE(tmp);
}

// Dividing Strings into Substrings

/**
 * <p>Returns an array of [NSString]s representing substrings of this string
 * that are separated by characters in the set (which must not be nil).
 * If there are no occurrences of separator, the whole string is
 * returned.  If string begins or ends with separator, empty strings will
 * be returned for those positions.</p>
 */
- (NSArray *) componentsSeparatedByCharactersInSet: (NSCharacterSet *)separator
{
  NSRange	search;
  NSRange	complete;
  NSRange	found;
  NSMutableArray *array;
  IF_NO_GC(NSAutoreleasePool *pool; NSUInteger count;)

  if (separator == nil)
    [NSException raise: NSInvalidArgumentException format: @"separator is nil"];

  array = [NSMutableArray array];
  IF_NO_GC(pool = [NSAutoreleasePool new]; count = 0;)
  search = NSMakeRange (0, [self length]);
  complete = search;
  found = [self rangeOfCharacterFromSet: separator];
  while (found.length != 0)
    {
      NSRange current;

      current = NSMakeRange (search.location,
	found.location - search.location);
      [array addObject: [self substringWithRange: current]];

      search = NSMakeRange (found.location + found.length,
	complete.length - found.location - found.length);
      found = [self rangeOfCharacterFromSet: separator
                                    options: 0
                                      range: search];
      IF_NO_GC(if (0 == count % 200) [pool emptyPool];)
    }
  // Add the last search string range
  [array addObject: [self substringWithRange: search]];
  IF_NO_GC([pool release];)
  // FIXME: Need to make mutable array into non-mutable array?
  return array;
}

/**
 * <p>Returns an array of [NSString]s representing substrings of this string
 * that are separated by separator (which itself is never returned in the
 * array).  If there are no occurrences of separator, the whole string is
 * returned.  If string begins or ends with separator, empty strings will
 * be returned for those positions.</p>
 * <p>Note, use an [NSScanner] if you need more sophisticated parsing.</p>
 */
- (NSArray*) componentsSeparatedByString: (NSString*)separator
{
  NSRange	search;
  NSRange	complete;
  NSRange	found;
  NSMutableArray *array = [NSMutableArray array];

  search = NSMakeRange (0, [self length]);
  complete = search;
  found = [self rangeOfString: separator
                      options: 0
                        range: search
                       locale: nil];
  while (found.length != 0)
    {
      NSRange current;

      current = NSMakeRange (search.location,
	found.location - search.location);
      [array addObject: [self substringWithRange: current]];

      search = NSMakeRange (found.location + found.length,
	complete.length - found.location - found.length);
      found = [self rangeOfString: separator
			  options: 0
			    range: search
                           locale: nil];
    }
  // Add the last search string range
  [array addObject: [self substringWithRange: search]];

  // FIXME: Need to make mutable array into non-mutable array?
  return array;
}

- (NSString*) stringByReplacingOccurrencesOfString: (NSString*)replace
                                        withString: (NSString*)by
                                           options: (NSStringCompareOptions)opts
                                             range: (NSRange)searchRange
{
  id copy;

  copy = [[[GSMutableStringClass allocWithZone: NSDefaultMallocZone()]
    initWithString: self] autorelease];
  [copy replaceOccurrencesOfString: replace
                        withString: by
                           options: opts
                             range: searchRange];
  return GS_IMMUTABLE(copy);
}

- (NSString*) stringByReplacingOccurrencesOfString: (NSString*)replace
                                        withString: (NSString*)by
{
  return [self 
      stringByReplacingOccurrencesOfString: replace
                                withString: by
                                   options: 0
                                     range: NSMakeRange(0, [self length])];
}

/**
 * Returns a new string where the substring in the given range is replaced by 
 * the passed string. 
 */
- (NSString*) stringByReplacingCharactersInRange: (NSRange)aRange 
                                      withString: (NSString*)by
{
  id	copy;

  copy = [[[GSMutableStringClass allocWithZone: NSDefaultMallocZone()]
    initWithString: self] autorelease];
  [copy replaceCharactersInRange: aRange withString: by];
  return GS_IMMUTABLE(copy);
}

/**
 * Returns a substring of the receiver from character at the specified
 * index to the end of the string.<br />
 * So, supplying an index of 3 would return a substring consisting of
 * the entire string apart from the first three character (those would
 * be at index 0, 1, and 2).<br />
 * If the supplied index is greater than or equal to the length of the
 * receiver an exception is raised.
 */
- (NSString*) substringFromIndex: (NSUInteger)index
{
  return [self substringWithRange: ((NSRange){index, [self length]-index})];
}

/**
 * Returns a substring of the receiver from the start of the
 * string to (but not including) the specified index position.<br />
 * So, supplying an index of 3 would return a substring consisting of
 * the first three characters of the receiver.<br />
 * If the supplied index is greater than the length of the receiver
 * an exception is raised.
 */
- (NSString*) substringToIndex: (NSUInteger)index
{
  return [self substringWithRange: ((NSRange){0,index})];
}

/**
 * An obsolete name for -substringWithRange: ... deprecated.
 */
- (NSString*) substringFromRange: (NSRange)aRange
{
  return [self substringWithRange: aRange];
}

/**
 * Returns a substring of the receiver containing the characters
 * in aRange.<br />
 * If aRange specifies any character position not
 * present in the receiver, an exception is raised.<br />
 * If aRange has a length of zero, an empty string is returned.
 */
- (NSString*) substringWithRange: (NSRange)aRange
{
  unichar	*buf;
  id		ret;
  unsigned	len = [self length];

  GS_RANGE_CHECK(aRange, len);

  if (aRange.length == 0)
    return @"";
  buf = NSZoneMalloc([self zone], sizeof(unichar)*aRange.length);
  [self getCharacters: buf range: aRange];
  ret = [[NSStringClass allocWithZone: NSDefaultMallocZone()]
    initWithCharactersNoCopy: buf length: aRange.length freeWhenDone: YES];
  return AUTORELEASE(ret);
}

// Finding Ranges of Characters and Substrings

/**
 * Returns position of first character in this string that is in aSet.
 * Positions start at 0.  If the character is a composed character sequence,
 * the range returned will contain the whole sequence, else just the character
 * itself.
 */
- (NSRange) rangeOfCharacterFromSet: (NSCharacterSet*)aSet
{
  NSRange all = NSMakeRange(0, [self length]);

  return [self rangeOfCharacterFromSet: aSet
			       options: 0
				 range: all];
}

/**
 * Returns position of first character in this string that is in aSet.
 * Positions start at 0.  If the character is a composed character sequence,
 * the range returned will contain the whole sequence, else just the character
 * itself.  mask may contain <code>NSCaseInsensitiveSearch</code>,
 * <code>NSLiteralSearch</code> (don't consider alternate forms of composed
 * characters equal), or <code>NSBackwardsSearch</code> (search from end of
 * string).
 */
- (NSRange) rangeOfCharacterFromSet: (NSCharacterSet*)aSet
			    options: (NSUInteger)mask
{
  NSRange all = NSMakeRange(0, [self length]);

  return [self rangeOfCharacterFromSet: aSet
			       options: mask
				 range: all];
}

/**
 * Returns position of first character in this string that is in aSet.
 * Positions start at 0.  If the character is a composed character sequence,
 * the range returned will contain the whole sequence, else just the character
 * itself.  mask may contain <code>NSCaseInsensitiveSearch</code>,
 * <code>NSLiteralSearch</code> (don't consider alternate forms of composed
 * characters equal), or <code>NSBackwardsSearch</code> (search from end of
 * string).  Search only carried out within aRange.
 */
- (NSRange) rangeOfCharacterFromSet: (NSCharacterSet*)aSet
			    options: (NSUInteger)mask
			      range: (NSRange)aRange
{
  unsigned int	i;
  unsigned int	start;
  unsigned int	stop;
  int		step;
  NSRange	range;
  unichar	(*cImp)(id, SEL, NSUInteger);
  BOOL		(*mImp)(id, SEL, unichar);

  i = [self length];
  GS_RANGE_CHECK(aRange, i);

  if ((mask & NSBackwardsSearch) == NSBackwardsSearch)
    {
      start = NSMaxRange(aRange)-1; stop = aRange.location-1; step = -1;
    }
  else
    {
      start = aRange.location; stop = NSMaxRange(aRange); step = 1;
    }
  range.location = NSNotFound;
  range.length = 0;

  cImp = (unichar(*)(id,SEL,NSUInteger))
    [self methodForSelector: caiSel];
  mImp = (BOOL(*)(id,SEL,unichar))
    [aSet methodForSelector: cMemberSel];

  for (i = start; i != stop; i += step)
    {
      unichar letter = (unichar)(*cImp)(self, caiSel, i);

      if ((*mImp)(aSet, cMemberSel, letter))
	{
	  range = NSMakeRange(i, 1);
	  break;
	}
    }

  return range;
}

/**
 * Invokes -rangeOfString:options: with no options.
 */
- (NSRange) rangeOfString: (NSString*)string
{
  NSRange	all = NSMakeRange(0, [self length]);

  return [self rangeOfString: string
		     options: 0
		       range: all
                      locale: nil];
}

/**
 * Invokes -rangeOfString:options:range: with the range set
 * set to the range of the whole of the receiver.
 */
- (NSRange) rangeOfString: (NSString*)string
		  options: (NSUInteger)mask
{
  NSRange	all = NSMakeRange(0, [self length]);

  return [self rangeOfString: string
		     options: mask
		       range: all
                      locale: nil];
}

/**
 * Returns the range giving the location and length of the first
 * occurrence of aString within aRange.
 * <br/>
 * If aString does not exist in the receiver (an empty
 * string is never considered to exist in the receiver),
 * the length of the returned range is zero.
 * <br/>
 * If aString is nil, an exception is raised.
 * <br/>
 * If any part of aRange lies outside the range of the
 * receiver, an exception is raised.
 * <br/>
 * The options mask may contain the following options -
 * <list>
 *   <item><code>NSCaseInsensitiveSearch</code></item>
 *   <item><code>NSLiteralSearch</code></item>
 *   <item><code>NSBackwardsSearch</code></item>
 *   <item><code>NSAnchoredSearch</code></item>
 * </list>
 * The <code>NSAnchoredSearch</code> option means aString must occur at the
 * beginning (or end, if <code>NSBackwardsSearch</code> is also given) of the
 * string.  Options should be OR'd together using <code>'|'</code>.
 */
- (NSRange) rangeOfString: (NSString *)aString
		  options: (NSUInteger)mask
		    range: (NSRange)aRange
{
  return [self rangeOfString: aString
                     options: mask
                       range: aRange
		      locale: nil];
}

- (NSRange) rangeOfString: (NSString *)aString
                  options: (NSStringCompareOptions)mask
                    range: (NSRange)searchRange
                   locale: (NSLocale *)locale
{
  NSUInteger    length = [self length];
  NSUInteger    countOther;

  GS_RANGE_CHECK(searchRange, length);
  if (aString == nil)
    [NSException raise: NSInvalidArgumentException format: @"range of nil"];

  if ((mask & NSRegularExpressionSearch) == NSRegularExpressionSearch)
    {
      NSRange			r = {NSNotFound, 0};
      NSError			*e = nil;
      NSUInteger		options = 0;
      NSRegularExpression	*regex = [NSRegularExpression alloc];

      if ((mask & NSCaseInsensitiveSearch) == NSCaseInsensitiveSearch)
	{
	  options |= NSRegularExpressionCaseInsensitive;
	}
      regex = [regex initWithPattern: aString options: options error: &e];
      if (nil == e)
	{
	  options = ((mask & NSAnchoredSearch) == NSAnchoredSearch)
	    ? NSMatchingAnchored : 0;
	  r = [regex rangeOfFirstMatchInString: self
				       options: options
					 range: searchRange];
	}
      [regex release];
      return r;
    }

  countOther = [aString length];

  /* A zero length string is always found at the start of the given range.
   */
  if (0 == countOther)
    {
      if ((mask & NSBackwardsSearch) == NSBackwardsSearch)
        {
          searchRange.location += searchRange.length;
        }
      searchRange.length = 0;
      return searchRange;
    }

  /* If the string to search for is a single codepoint which is not
   * decomposable to a sequence, then it can only match the identical
   * codepoint, so we can perform the much cheaper literal search.
   */
  if (1 == countOther)
    {
      unichar   u = [aString characterAtIndex: 0];

      if ((mask & NSLiteralSearch) == NSLiteralSearch || uni_is_decomp(u))
        {
          NSRange   result;

          if (searchRange.length < countOther)
            {
              /* Range to search is smaller than string to look for.
               */
              result = NSMakeRange(NSNotFound, 0);
            }
          else if ((mask & NSAnchoredSearch) == NSAnchoredSearch
            || searchRange.length == 1)
            {
              /* Range to search is a single character.
               */
              if ((mask & NSBackwardsSearch) == NSBackwardsSearch)
                {
                  searchRange.location = NSMaxRange(searchRange) - 1;
                }
              if ((mask & NSCaseInsensitiveSearch) == NSCaseInsensitiveSearch)
                {
                  u = uni_toupper(u);
                  if (uni_toupper([self characterAtIndex: searchRange.location])
                     == u)
                    {
                      result = searchRange;
                    }
                  else
                    {
                      result = NSMakeRange(NSNotFound, 0);
                    }
                }
              else
                {
                  if ([self characterAtIndex: searchRange.location] == u)
                    {
                      result = searchRange;
                    }
                  else
                    {
                      result = NSMakeRange(NSNotFound, 0);
                    }
                }
            }
          else
            {
              NSUInteger    pos;
              NSUInteger    end;

              /* Range to search is bigger than string to look for.
               */
              GS_BEGINITEMBUF2(charsSelf, (searchRange.length*sizeof(unichar)),
                unichar)
              [self getCharacters: charsSelf range: searchRange];
              end = searchRange.length;
              if ((mask & NSCaseInsensitiveSearch) == NSCaseInsensitiveSearch)
                {
                  u = uni_toupper(u);
                  if ((mask & NSBackwardsSearch) == NSBackwardsSearch)
                    {
                      pos = end;
                      while (pos-- > 0)
                        {
                          if (uni_toupper(charsSelf[pos]) == u)
                            {
                              break;
                            }
                        }
                    }
                  else
                    {
                      pos = 0;
                      while (pos < end)
                        {
                          if (uni_toupper(charsSelf[pos]) == u)
                            {
                              break;
                            }
                          pos++;
                        }                        
                    }
                }
              else
                {
                  if ((mask & NSBackwardsSearch) == NSBackwardsSearch)
                    {
                      pos = end;
                      while (pos-- > 0)
                        {
                          if (charsSelf[pos] == u)
                            {
                              break;
                            }
                        }
                    }
                  else
                    {
                      pos = 0;
                      while (pos < end)
                        {
                          if (charsSelf[pos] == u)
                            {
                              break;
                            }
                          pos++;
                        }                        
                    }
                }
              GS_ENDITEMBUF2()

              if (pos >= end)
                {
                  result = NSMakeRange(NSNotFound, 0);
                }
              else
                {
                  result = NSMakeRange(searchRange.location + pos, countOther);
                }
            }
          return result;
        }
    }

  if ((mask & NSLiteralSearch) == NSLiteralSearch)
    {
      NSRange   result;
      BOOL      insensitive;

      if ((mask & NSCaseInsensitiveSearch) == NSCaseInsensitiveSearch)
        {
          insensitive = YES;
        }
      else
        {
          insensitive = NO;
        }

      if (searchRange.length < countOther)
        {
          /* Range to search is smaller than string to look for.
           */
          result = NSMakeRange(NSNotFound, 0);
        }
      else
        {
          GS_BEGINITEMBUF(charsOther, (countOther*sizeof(unichar)), unichar)

          [aString getCharacters: charsOther range: NSMakeRange(0, countOther)];
          if (YES == insensitive)
            {
              NSUInteger        index;

              /* Make the substring we are searching for be uppercase.
               */
              for (index = 0; index < countOther; index++)
                {
                  charsOther[index] = uni_toupper(charsOther[index]);
                }
            }
          if ((mask & NSAnchoredSearch) == NSAnchoredSearch
            || searchRange.length == countOther)
            {
              /* Range to search is same size as string to look for.
               */
              GS_BEGINITEMBUF2(charsSelf, (countOther*sizeof(unichar)), unichar)
              if ((mask & NSBackwardsSearch) == NSBackwardsSearch)
                {
                  searchRange.location = NSMaxRange(searchRange) - countOther;
                  searchRange.length = countOther;
                }
              else
                {
                  searchRange.length = countOther;
                }
              [self getCharacters: charsSelf range: searchRange];
              if (YES == insensitive)
                {
                  NSUInteger    index;

                  for (index = 0; index < countOther; index++)
                    {
                      if (uni_toupper(charsSelf[index]) != charsOther[index])
                        {
                          break;
                        }
                    }
                  if (index < countOther)
                    {
                      result = NSMakeRange(NSNotFound, 0);
                    }
                  else
                    {
                      result = searchRange;
                    }
                }
              else
                {
                  if (memcmp(&charsSelf[0], &charsOther[0],
                    countOther * sizeof(unichar)) == 0)
                    {
                      result = searchRange;
                    }
                  else
                    {
                      result = NSMakeRange(NSNotFound, 0);
                    }
                }
              GS_ENDITEMBUF2()
            }
          else
            {
              NSUInteger    pos;
              NSUInteger    end;

              end = searchRange.length - countOther + 1;
              if ((mask & NSBackwardsSearch) == NSBackwardsSearch)
                {
                  pos = end;
                }
              else
                {
                  pos = 0;
                }
              /* Range to search is bigger than string to look for.
               */
              GS_BEGINITEMBUF2(charsSelf, (searchRange.length*sizeof(unichar)),
                unichar)
              [self getCharacters: charsSelf range: searchRange];

              if (YES == insensitive)
                {
                  NSUInteger        count;
                  NSUInteger        index;

                  /* Make things uppercase in the string being searched
                   * Start with all but one of the characters in a substring
                   * and we'll uppercase one more character each time we do
                   * a comparison.
                   */
                  index = pos;
                  for (count = 1; count < countOther; count++)
                    {
                      charsSelf[index] = uni_toupper(charsSelf[index]);
                      index++;
                    }
                }

              if ((mask & NSBackwardsSearch) == NSBackwardsSearch)
                {
                  if (YES == insensitive)
                    {
                      while (pos-- > 0)
                        {
                          charsSelf[pos] = uni_toupper(charsSelf[pos]);
                          if (memcmp(&charsSelf[pos], charsOther,
                            countOther * sizeof(unichar)) == 0)
                            {
                              break;
                            }
                        }
                    }
                  else
                    {
                      while (pos-- > 0)
                        {
                          if (memcmp(&charsSelf[pos], charsOther,
                            countOther * sizeof(unichar)) == 0)
                            {
                              break;
                            }
                        }
                    }
                }
              else
                {
                  if (YES == insensitive)
                    {
                      while (pos < end)
                        {
                          charsSelf[pos + countOther - 1]
                            = uni_toupper(charsSelf[pos + countOther - 1]);
                          if (memcmp(&charsSelf[pos], charsOther,
                            countOther * sizeof(unichar)) == 0)
                            {
                              break;
                            }
                          pos++;
                        }                        
                    }
                  else
                    {
                      while (pos < end)
                        {
                          if (memcmp(&charsSelf[pos], charsOther,
                            countOther * sizeof(unichar)) == 0)
                            {
                              break;
                            }
                          pos++;
                        }                        
                    }
                }

              if (pos >= end)
                {
                  result = NSMakeRange(NSNotFound, 0);
                }
              else
                {
                  result = NSMakeRange(searchRange.location + pos, countOther);
                }
              GS_ENDITEMBUF2()
            }
          GS_ENDITEMBUF()
        }
      return result;
    }

#if GS_USE_ICU == 1
    {
      UCollator *coll = GSICUCollatorOpen(mask, locale);

      if (NULL != coll)
	{
	  NSRange       result = NSMakeRange(NSNotFound, 0);
	  UErrorCode    status = U_ZERO_ERROR; 
	  NSUInteger    countSelf = searchRange.length;
	  UStringSearch *search = NULL;
          GS_BEGINITEMBUF(charsSelf, (countSelf * sizeof(unichar)), unichar)
          GS_BEGINITEMBUF2(charsOther, (countOther * sizeof(unichar)), unichar)

	  // Copy to buffer
      
	  [self getCharacters: charsSelf range: searchRange];
	  [aString getCharacters: charsOther range: NSMakeRange(0, countOther)];
	  
	  search = usearch_openFromCollator(charsOther, countOther,
					    charsSelf, countSelf,
					    coll, NULL, &status);
	  if (search != NULL && U_SUCCESS(status))
	    {
	      int32_t matchLocation;
	      int32_t matchLength;

	      if ((mask & NSBackwardsSearch) == NSBackwardsSearch)
		{		
		  matchLocation = usearch_last(search, &status);
		}
	      else
		{
		  matchLocation = usearch_first(search, &status);
		}
	      matchLength = usearch_getMatchedLength(search);
	      
	      if (matchLocation != USEARCH_DONE && matchLength != 0)
		{
		  if ((mask & NSAnchoredSearch) == NSAnchoredSearch)
		    {
		      if ((mask & NSBackwardsSearch) == NSBackwardsSearch)
			{
			  if (matchLocation + matchLength
                            == NSMaxRange(searchRange))
                            {
                              result = NSMakeRange(searchRange.location
                                + matchLocation, matchLength);
                            }
			}
		      else
			{
			  if (matchLocation == 0)
                            {
                              result = NSMakeRange(searchRange.location
                                + matchLocation, matchLength);
                            }
			}
		    }
		  else 
		    {
		      result = NSMakeRange(searchRange.location
                        + matchLocation, matchLength);
		    }
		}
	    }
          GS_ENDITEMBUF2()
          GS_ENDITEMBUF()
	  usearch_close(search);
	  ucol_close(coll);
	  return result;
	}
    }
#endif

  return strRangeNsNs(self, aString, mask, searchRange);
}

- (NSUInteger) indexOfString: (NSString *)substring
{
  NSRange range = {0, [self length]};

  range = [self rangeOfString: substring options: 0 range: range locale: nil];
  return range.length ? range.location : NSNotFound;
}

- (NSUInteger) indexOfString: (NSString*)substring
                   fromIndex: (NSUInteger)index
{
  NSRange range = {index, [self length] - index};

  range = [self rangeOfString: substring options: 0 range: range locale: nil];
  return range.length ? range.location : NSNotFound;
}

// Determining Composed Character Sequences

/**
 * Unicode utility method.  If character at anIndex is part of a composed
 * character sequence anIndex (note indices start from 0), returns the full
 * range of this sequence.
 */
- (NSRange) rangeOfComposedCharacterSequenceAtIndex: (NSUInteger)anIndex
{
  unsigned	start;
  unsigned	end;
  unsigned	length = [self length];
  unichar	ch;
  unichar	(*caiImp)(NSString*, SEL, NSUInteger);

  if (anIndex >= length)
    [NSException raise: NSRangeException format:@"Invalid location."];
  caiImp = (unichar (*)(NSString*,SEL,NSUInteger))
    [self methodForSelector: caiSel];

  for (start = anIndex; start > 0; start--)
    {
      ch = (*caiImp)(self, caiSel, start);
      if (uni_isnonsp(ch) == NO)
        break;
    }
  for (end = start+1; end < length; end++)
    {
      ch = (*caiImp)(self, caiSel, end);
      if (uni_isnonsp(ch) == NO)
        break;
    }

  return NSMakeRange(start, end-start);
}

- (NSRange) rangeOfComposedCharacterSequencesForRange: (NSRange)range
{
  NSRange startRange = [self rangeOfComposedCharacterSequenceAtIndex: range.location];

  if (NSMaxRange(startRange) >= NSMaxRange(range))
    {
      return startRange;
    }
  else
    {
      NSRange endRange = [self rangeOfComposedCharacterSequenceAtIndex: NSMaxRange(range) - 1];

      return NSUnionRange(startRange, endRange);
    }
}

// Identifying and Comparing Strings

/**
 * <p>Compares this instance with aString.  Returns
 * <code>NSOrderedAscending</code>, <code>NSOrderedDescending</code>, or
 * <code>NSOrderedSame</code>, depending on whether this instance occurs
 * before or after string in lexical order, or is equal to it.</p>
 */
- (NSComparisonResult) compare: (NSString*)aString
{
  return [self compare: aString options: 0];
}

/**
 * <p>Compares this instance with aString.  mask may be either
 * <code>NSCaseInsensitiveSearch</code> or <code>NSLiteralSearch</code>.  The
 * latter requests a literal byte-by-byte comparison, which is fastest but may
 * return inaccurate results in cases where two different composed character
 * sequences may be used to express the same character.</p>
 */
- (NSComparisonResult) compare: (NSString*)aString
		       options: (NSUInteger)mask
{
  return [self compare: aString options: mask
		 range: ((NSRange){0, [self length]})];
}

/**
 * <p>Compares this instance with string.  mask may be either
 * <code>NSCaseInsensitiveSearch</code> or <code>NSLiteralSearch</code>.  The
 * latter requests a literal byte-by-byte comparison, which is fastest but may
 * return inaccurate results in cases where two different composed character
 * sequences may be used to express the same character.  aRange refers
 * to this instance, and should be set to 0..length to compare the whole
 * string.</p>
 */
// xxx Should implement full POSIX.2 collate
- (NSComparisonResult) compare: (NSString*)aString
		       options: (NSUInteger)mask
			 range: (NSRange)aRange
{
  return [self compare: aString
	       options: mask
		 range: aRange
		locale: nil];
}

/**
 *  Returns whether this string starts with aString.
 */
- (BOOL) hasPrefix: (NSString*)aString
{
  NSRange	range = NSMakeRange(0, [self length]);
  NSUInteger    mask = NSLiteralSearch | NSAnchoredSearch;

  range = [self rangeOfString: aString
                      options: mask
                        range: range
                       locale: nil];
  return (range.length > 0) ? YES : NO;
}

/**
 *  Returns whether this string ends with aString.
 */
- (BOOL) hasSuffix: (NSString*)aString
{
  NSRange	range = NSMakeRange(0, [self length]);
  NSUInteger    mask = NSLiteralSearch | NSAnchoredSearch | NSBackwardsSearch;

  range = [self rangeOfString: aString
                      options: mask
                        range: range
                       locale: nil];
  return (range.length > 0) ? YES : NO;
}

/**
 *  Returns whether the receiver and an anObject are equals as strings.
 *  If anObject isn't an NSString, returns NO.
 */
- (BOOL) isEqual: (id)anObject
{
  if (anObject == self)
    {
      return YES;
    }
  if (anObject != nil && [anObject isKindOfClass: NSStringClass])
    {
      return [self isEqualToString: anObject];
    }
  return NO;
}

/**
 *  Returns whether this instance is equal as a string to aString.  See also
 *  -compare: and related methods.
 */
- (BOOL) isEqualToString: (NSString*)aString
{
  if (aString == self)
    {
      return YES;
    }
  if (nil == aString || [self hash] != [aString hash])
    {
      return NO;
    }
  if (strCompNsNs(self, aString, 0, (NSRange){0, [self length]})
    == NSOrderedSame)
    {
      return YES;
    }
  return NO;
}

/**
 * Return 28-bit hash value (in 32-bit integer).  The top few bits are used
 * for other purposes in a bitfield in the concrete string subclasses, so we
 * must not use the full unsigned integer.
 */
- (NSUInteger) hash
{
  uint32_t	ret = 0;
  int   	len = (int)[self length];

  if (len > 0)
    {
      static const int buf_size = 64;
      unichar		buf[buf_size];
      int idx = 0;
      uint32_t s0 = 0;
      uint32_t s1 = 0;

      while (idx < len)
	{
	  int l = MIN(len-idx, buf_size);
	  [self getCharacters: buf range: NSMakeRange(idx,l)];
	  GSPrivateIncrementalHash(&s0, &s1, buf, l * sizeof(unichar));
	  idx += l;
	}

      ret = GSPrivateFinishHash(s0, s1, len * sizeof(unichar));

      /*
       * The hash caching in our concrete string classes uses zero to denote
       * an empty cache value, so we MUST NOT return a hash of zero.
       */
      ret &= 0x0fffffff;
      if (ret == 0)
	{
	  ret = 0x0fffffff;
	}
      return ret;
    }
  else
    {
      return 0x0ffffffe;	/* Hash for an empty string.	*/
    }
}

// Getting a Shared Prefix

/**
 *  Returns the largest initial portion of this instance shared with aString.
 *  mask may be either <code>NSCaseInsensitiveSearch</code> or
 *  <code>NSLiteralSearch</code>.  The latter requests a literal byte-by-byte
 *  comparison, which is fastest but may return inaccurate results in cases
 *  where two different composed character sequences may be used to express
 *  the same character.
 */
- (NSString*) commonPrefixWithString: (NSString*)aString
			     options: (NSUInteger)mask
{
  if (mask & NSLiteralSearch)
    {
      int prefix_len = 0;
      unsigned	length = [self length];
      unsigned	aLength = [aString length];
      unichar *u;
      unichar a1[length+1];
      unichar *s1 = a1;
      unichar a2[aLength+1];
      unichar *s2 = a2;

      [self getCharacters: s1 range: ((NSRange){0, length})];
      s1[length] = (unichar)0;
      [aString getCharacters: s2 range: ((NSRange){0, aLength})];
      s2[aLength] = (unichar)0;
      u = s1;

      if (mask & NSCaseInsensitiveSearch)
	{
	  while (*s1 && *s2 && (uni_tolower(*s1) == uni_tolower(*s2)))
	    {
	      s1++;
	      s2++;
	      prefix_len++;
	    }
	}
      else
	{
	  while (*s1 && *s2 && (*s1 == *s2))
	    {
	      s1++;
	      s2++;
	      prefix_len++;
	    }
	}
      return [NSStringClass stringWithCharacters: u length: prefix_len];
    }
  else
    {
      unichar	(*scImp)(NSString*, SEL, NSUInteger);
      unichar	(*ocImp)(NSString*, SEL, NSUInteger);
      void	(*sgImp)(NSString*, SEL, unichar*, NSRange) = 0;
      void	(*ogImp)(NSString*, SEL, unichar*, NSRange) = 0;
      NSRange	(*srImp)(NSString*, SEL, NSUInteger) = 0;
      NSRange	(*orImp)(NSString*, SEL, NSUInteger) = 0;
      BOOL	gotRangeImps = NO;
      BOOL	gotFetchImps = NO;
      NSRange	sRange;
      NSRange	oRange;
      unsigned	sLength = [self length];
      unsigned	oLength = [aString length];
      unsigned	sIndex = 0;
      unsigned	oIndex = 0;

      if (!sLength)
	return IMMUTABLE(self);
      if (!oLength)
	return IMMUTABLE(aString);

      scImp = (unichar (*)(NSString*,SEL,NSUInteger))
	[self methodForSelector: caiSel];
      ocImp = (unichar (*)(NSString*,SEL,NSUInteger))
	[aString methodForSelector: caiSel];

      while ((sIndex < sLength) && (oIndex < oLength))
	{
	  unichar	sc = (*scImp)(self, caiSel, sIndex);
	  unichar	oc = (*ocImp)(aString, caiSel, oIndex);

	  if (sc == oc)
	    {
	      sIndex++;
	      oIndex++;
	    }
	  else if ((mask & NSCaseInsensitiveSearch)
	    && (uni_tolower(sc) == uni_tolower(oc)))
	    {
	      sIndex++;
	      oIndex++;
	    }
	  else
	    {
	      if (gotRangeImps == NO)
		{
		  gotRangeImps = YES;
		  srImp=(NSRange (*)())[self methodForSelector: ranSel];
		  orImp=(NSRange (*)())[aString methodForSelector: ranSel];
		}
	      sRange = (*srImp)(self, ranSel, sIndex);
	      oRange = (*orImp)(aString, ranSel, oIndex);

	      if ((sRange.length < 2) || (oRange.length < 2))
		return [self substringWithRange: NSMakeRange(0, sIndex)];
	      else
		{
		  GSEQ_MAKE(sBuf, sSeq, sRange.length);
		  GSEQ_MAKE(oBuf, oSeq, oRange.length);

		  if (gotFetchImps == NO)
		    {
		      gotFetchImps = YES;
		      sgImp=(void (*)())[self methodForSelector: gcrSel];
		      ogImp=(void (*)())[aString methodForSelector: gcrSel];
		    }
		  (*sgImp)(self, gcrSel, sBuf, sRange);
		  (*ogImp)(aString, gcrSel, oBuf, oRange);

		  if (GSeq_compare(&sSeq, &oSeq) == NSOrderedSame)
		    {
		      sIndex += sRange.length;
		      oIndex += oRange.length;
		    }
		  else if (mask & NSCaseInsensitiveSearch)
		    {
		      GSeq_lowercase(&sSeq);
		      GSeq_lowercase(&oSeq);
		      if (GSeq_compare(&sSeq, &oSeq) == NSOrderedSame)
			{
			  sIndex += sRange.length;
			  oIndex += oRange.length;
			}
		      else
			return [self substringWithRange: NSMakeRange(0,sIndex)];
		    }
		  else
		    return [self substringWithRange: NSMakeRange(0,sIndex)];
		}
	    }
	}
      return [self substringWithRange: NSMakeRange(0, sIndex)];
    }
}

/**
 * Determines the smallest range of lines containing aRange and returns
 * the information as a range.<br />
 * Calls -getLineStart:end:contentsEnd:forRange: to do the work.
 */
- (NSRange) lineRangeForRange: (NSRange)aRange
{
  NSUInteger startIndex;
  NSUInteger lineEndIndex;

  [self getLineStart: &startIndex
                 end: &lineEndIndex
         contentsEnd: NULL
            forRange: aRange];
  return NSMakeRange(startIndex, lineEndIndex - startIndex);
}

- (void) _getStart: (NSUInteger*)startIndex
	       end: (NSUInteger*)lineEndIndex
       contentsEnd: (NSUInteger*)contentsEndIndex
	  forRange: (NSRange)aRange
	   lineSep: (BOOL)flag
{
  unichar	thischar;
  unsigned	start, end, len, termlen;
  unichar	(*caiImp)(NSString*, SEL, NSUInteger);

  len = [self length];
  GS_RANGE_CHECK(aRange, len);

  caiImp = (unichar (*)())[self methodForSelector: caiSel];
  /* Place aRange.location at the beginning of a CR-LF sequence */
  if (aRange.location > 0 && aRange.location < len
    && (*caiImp)(self, caiSel, aRange.location - 1) == (unichar)'\r'
    && (*caiImp)(self, caiSel, aRange.location) == (unichar)'\n')
    {
      aRange.location--;
    }
  start = aRange.location;

  if (startIndex)
    {
      if (start == 0)
	{
	  *startIndex = 0;
	}
      else
	{
	  start--;
	  while (start > 0)
	    {
	      BOOL	done = NO;

	      thischar = (*caiImp)(self, caiSel, start);
	      switch (thischar)
		{
		  case (unichar)0x000A:
		  case (unichar)0x000D:
		  case (unichar)0x2029:
		    done = YES;
		    break;
		  case (unichar)0x2028:
		    if (flag)
		      {
			done = YES;
			break;
		      }
		  default:
		    start--;
		    break;
		}
	      if (done)
		break;
	    }
	  if (start == 0)
	    {
	      thischar = (*caiImp)(self, caiSel, start);
	      switch (thischar)
		{
		  case (unichar)0x000A:
		  case (unichar)0x000D:
		  case (unichar)0x2029:
		    start++;
		    break;
		  case (unichar)0x2028:
		    if (flag)
		      {
			start++;
			break;
		      }
		  default:
		    break;
		}
	    }
	  else
	    {
	      start++;
	    }
	  *startIndex = start;
	}
    }

  if (lineEndIndex || contentsEndIndex)
    {
      BOOL found = NO;
      end = aRange.location;
      if (aRange.length)
        {
          end += (aRange.length - 1);
        }
      while (end < len)
	{
	   thischar = (*caiImp)(self, caiSel, end);
	   switch (thischar)
	     {
	       case (unichar)0x000A:
	       case (unichar)0x000D:
	       case (unichar)0x2029:
		 found = YES;
		 break;
	       case (unichar)0x2028:
		 if (flag)
		   {
		     found = YES;
		     break;
		   }
	       default:
		 break;
	     }
	   end++;
	   if (found)
	     break;
	}
      termlen = 1;
      if (lineEndIndex)
	{
	  if (end < len
	    && ((*caiImp)(self, caiSel, end-1) == (unichar)0x000D)
	    && ((*caiImp)(self, caiSel, end) == (unichar)0x000A))
	    {
	      *lineEndIndex = ++end;
	      termlen = 2;
	    }
	  else
	    {
	      *lineEndIndex = end;
	    }
	}
      if (contentsEndIndex)
	{
	  if (found)
	    {
	      *contentsEndIndex = end-termlen;
	    }
	  else
	    {
	      /* xxx OPENSTEP documentation does not say what to do if last
		 line is not terminated. Assume this */
	      *contentsEndIndex = end;
	    }
	}
    }
}

/**
 * Determines the smallest range of lines containing aRange and returns
 * the locations in that range.<br />
 * Lines are delimited by any of these character sequences, the longest
 * (CRLF) sequence preferred.
 * <list>
 *   <item>U+000A (linefeed)</item>
 *   <item>U+000D (carriage return)</item>
 *   <item>U+2028 (Unicode line separator)</item>
 *   <item>U+2029 (Unicode paragraph separator)</item>
 *   <item>U+000D U+000A (CRLF)</item>
 * </list>
 * The index of the first character of the line at or before aRange is
 * returned in startIndex.<br />
 * The index of the first character of the next line after the line terminator
 * is returned in endIndex.<br />
 * The index of the last character before the line terminator is returned
 * contentsEndIndex.<br />
 * Raises an NSRangeException if the range is invalid, but permits the index
 * arguments to be null pointers (in which case no value is returned in that
 * argument).
 */
- (void) getLineStart: (NSUInteger *)startIndex
                  end: (NSUInteger *)lineEndIndex
          contentsEnd: (NSUInteger *)contentsEndIndex
	     forRange: (NSRange)aRange
{
  [self _getStart: startIndex
	      end: lineEndIndex
      contentsEnd: contentsEndIndex
	 forRange: aRange
	  lineSep: YES];
}

- (void) getParagraphStart: (NSUInteger *)startIndex 
                       end: (NSUInteger *)parEndIndex
               contentsEnd: (NSUInteger *)contentsEndIndex
                  forRange: (NSRange)range
{
  [self _getStart: startIndex
	      end: parEndIndex
      contentsEnd: contentsEndIndex
         forRange: range
	  lineSep: NO];
}

// Changing Case

/**
 * Returns version of string in which each whitespace-delimited <em>word</em>
 * is capitalized (not every letter).  Conversion to capitals is done in a
 * unicode-compliant manner but there may be exceptional cases where behavior
 * is not what is desired.
 */
// xxx There is more than this in word capitalization in Unicode,
// but this will work in most cases
- (NSString*) capitalizedString
{
  unichar	*s;
  unsigned	count = 0;
  BOOL		found = YES;
  unsigned	len = [self length];

  if (len == 0)
    return IMMUTABLE(self);

  s = NSZoneMalloc([self zone], sizeof(unichar)*len);
  [self getCharacters: s range: ((NSRange){0, len})];
  while (count < len)
    {
      if (GS_IS_WHITESPACE(s[count]))
	{
	  count++;
	  found = YES;
	  while (count < len
	    && GS_IS_WHITESPACE(s[count]))
	    {
	      count++;
	    }
	}
      if (count < len)
	{
	  if (found)
	    {
	      s[count] = uni_toupper(s[count]);
	      count++;
	    }
	  else
	    {
	      while (count < len
		&& !GS_IS_WHITESPACE(s[count]))
		{
		  s[count] = uni_tolower(s[count]);
		  count++;
		}
	    }
	}
      found = NO;
    }
  return AUTORELEASE([[NSString allocWithZone: NSDefaultMallocZone()]
    initWithCharactersNoCopy: s length: len freeWhenDone: YES]);
}

/**
 * Returns a copy of the receiver with all characters converted
 * to lowercase.
 */
- (NSString*) lowercaseString
{
  static NSCharacterSet	*uc = nil;
  unichar	*s;
  unsigned	count;
  NSRange	start;
  unsigned	len = [self length];

  if (len == 0)
    {
      return IMMUTABLE(self);
    }
  if (uc == nil)
    {
      uc = RETAIN([NSCharacterSet uppercaseLetterCharacterSet]);
    }
  start = [self rangeOfCharacterFromSet: uc
				options: NSLiteralSearch
				  range: ((NSRange){0, len})];
  if (start.length == 0)
    {
      return IMMUTABLE(self);
    }
  s = NSZoneMalloc([self zone], sizeof(unichar)*len);
  [self getCharacters: s range: ((NSRange){0, len})];
  for (count = start.location; count < len; count++)
    {
      s[count] = uni_tolower(s[count]);
    }
  return AUTORELEASE([[NSStringClass allocWithZone: NSDefaultMallocZone()]
    initWithCharactersNoCopy: s length: len freeWhenDone: YES]);
}

/**
 * Returns a copy of the receiver with all characters converted
 * to uppercase.
 */
- (NSString*) uppercaseString
{
  static NSCharacterSet	*lc = nil;
  unichar	*s;
  unsigned	count;
  NSRange	start;
  unsigned	len = [self length];

  if (len == 0)
    {
      return IMMUTABLE(self);
    }
  if (lc == nil)
    {
      lc = RETAIN([NSCharacterSet lowercaseLetterCharacterSet]);
    }
  start = [self rangeOfCharacterFromSet: lc
				options: NSLiteralSearch
				  range: ((NSRange){0, len})];
  if (start.length == 0)
    {
      return IMMUTABLE(self);
    }
  s = NSZoneMalloc([self zone], sizeof(unichar)*len);
  [self getCharacters: s range: ((NSRange){0, len})];
  for (count = start.location; count < len; count++)
    {
      s[count] = uni_toupper(s[count]);
    }
  return AUTORELEASE([[NSStringClass allocWithZone: NSDefaultMallocZone()]
    initWithCharactersNoCopy: s length: len freeWhenDone: YES]);
}

// Storing the String

/** Returns <code>self</code>. */
- (NSString*) description
{
  return self;
}


// Getting C Strings

/**
 * Returns a pointer to a null terminated string of 16-bit unichar
 * The memory pointed to is not owned by the caller, so the
 * caller must copy its contents to keep it.
 */
- (const unichar*) unicharString
{
  NSMutableData	*data;
  unichar	*uniStr;

  GSOnceMLog(@"deprecated ... use cStringUsingEncoding:");

  data = [NSMutableData dataWithLength: ([self length] + 1) * sizeof(unichar)];
  uniStr = (unichar*)[data mutableBytes];
  if (uniStr != 0)
    {
      [self getCharacters: uniStr];
    }
  return uniStr;
}

/**
 * Returns a pointer to a null terminated string of 8-bit characters in the
 * default encoding.  The memory pointed to is not owned by the caller, so the
 * caller must copy its contents to keep it.  Raises an
 * <code>NSCharacterConversionException</code> if loss of information would
 * occur during conversion.  (See -canBeConvertedToEncoding: .)
 */
- (const char*) cString
{
  NSData	*d;
  NSMutableData	*m;

  d = [self dataUsingEncoding: _DefaultStringEncoding
	 allowLossyConversion: NO];
  if (d == nil)
    {
      [NSException raise: NSCharacterConversionException
		  format: @"unable to convert to cString"];
    }
  m = [d mutableCopy];
  [m appendBytes: "" length: 1];
  IF_NO_GC([m autorelease];)
  return (const char*)[m bytes];
}

/**
 * Returns a pointer to a null terminated string of characters in the
 * specified encoding.<br />
 * NB. under GNUstep you can used this to obtain a nul terminated utf-16
 * string (sixteen bit characters) as well as eight bit strings.<br />
 * The memory pointed to is not owned by the caller, so the
 * caller must copy its contents to keep it.<br />
 * Raises an <code>NSCharacterConversionException</code> if loss of
 * information would occur during conversion.
 */
- (const char*) cStringUsingEncoding: (NSStringEncoding)encoding
{
  NSMutableData	*m;

  if (NSUnicodeStringEncoding == encoding)
    {
      unichar	*u;
      unsigned	l;

      l = [self length];
      m = [NSMutableData dataWithLength: (l + 1) * sizeof(unichar)];
      u = (unichar*)[m mutableBytes];
      [self getCharacters: u];
      u[l] = 0;
    }
  else
    {
      NSData	*d;

      d = [self dataUsingEncoding: encoding allowLossyConversion: NO];
      if (d == nil)
	{
	  [NSException raise: NSCharacterConversionException
		      format: @"unable to convert to cString"];
	}
      m = [[d mutableCopy] autorelease];
      [m appendBytes: "" length: 1];
    }
  return (const char*)[m bytes];
}

/**
 * Returns the number of bytes needed to encode the receiver in the
 * specified encoding (without adding a nul character terminator).<br />
 * Returns 0 if the conversion is not possible.
 */
- (NSUInteger) lengthOfBytesUsingEncoding: (NSStringEncoding)encoding
{
  NSData	*d;

  d = [self dataUsingEncoding: encoding allowLossyConversion: NO];
  return [d length];
}

/**
 * Returns a size guaranteed to be large enough to encode the receiver in the
 * specified encoding (without adding a nul character terminator).  This may
 * be larger than the actual number of bytes needed.
 */
- (NSUInteger) maximumLengthOfBytesUsingEncoding: (NSStringEncoding)encoding
{
  if (encoding == NSUnicodeStringEncoding)
    return [self length] * 2;
  if (encoding == NSUTF8StringEncoding)
    return [self length] * 6;
  if (encoding == NSUTF7StringEncoding)
    return [self length] * 8;
  return [self length];				// Assume single byte/char
}

/**
 * Returns a C string converted using the default C string encoding, which may
 * result in information loss.  The memory pointed to is not owned by the
 * caller, so the caller must copy its contents to keep it.
 */
- (const char*) lossyCString
{
  NSData	*d;
  NSMutableData	*m;

  d = [self dataUsingEncoding: _DefaultStringEncoding
         allowLossyConversion: YES];
  m = [d mutableCopy];
  [m appendBytes: "" length: 1];
  IF_NO_GC([m autorelease];)
  return (const char*)[m bytes];
}

/**
 * Returns null-terminated UTF-8 version of this unicode string.  The char[]
 * memory comes from an autoreleased object, so it will eventually go out of
 * scope.
 */
- (const char *) UTF8String
{
  NSData	*d;
  NSMutableData	*m;

  d = [self dataUsingEncoding: NSUTF8StringEncoding
         allowLossyConversion: NO];
  m = [d mutableCopy];
  [m appendBytes: "" length: 1];
  IF_NO_GC([m autorelease];)
  return (const char*)[m bytes];
}

/**
 *  Returns length of a version of this unicode string converted to bytes
 *  using the default C string encoding.  If the conversion would result in
 *  information loss, the results are unpredictable.  Check
 *  -canBeConvertedToEncoding: first.
 */
- (NSUInteger) cStringLength
{
  NSData	*d;

  d = [self dataUsingEncoding: _DefaultStringEncoding
         allowLossyConversion: NO];
  return [d length];
}

/**
 * Deprecated ... do not use.<br />.
 * Use -getCString:maxLength:encoding: instead.
 */
- (void) getCString: (char*)buffer
{
  [self getCString: buffer maxLength: NSMaximumStringLength
	     range: ((NSRange){0, [self length]})
    remainingRange: NULL];
}

/**
 * Deprecated ... do not use.<br />.
 * Use -getCString:maxLength:encoding: instead.
 */
- (void) getCString: (char*)buffer
	  maxLength: (NSUInteger)maxLength
{
  [self getCString: buffer maxLength: maxLength
	     range: ((NSRange){0, [self length]})
    remainingRange: NULL];
}

/**
 * Retrieve up to maxLength bytes from the receiver into the buffer.<br />
 * In GNUstep, this method implements the actual behavior of the MacOS-X
 * method rather than it's documented behavior ...<br />
 * The maxLength argument must be the size (in bytes) of the area of
 * memory pointed to by the buffer argument.<br />
 * Returns YES on success.<br />
 * Returns NO if maxLength is too small to hold the entire string
 * including a terminating nul character.<br />
 * If it returns NO, the terminating nul will <em>not</em> have been
 * written to the buffer.<br />
 * Raises an exception if the string can not be converted to the
 * specified encoding without loss of information.<br />
 * eg. If the receiver is @"hello" then the provided buffer must be
 * at least six bytes long and the value of maxLength must be at least
 * six if NSASCIIStringEncoding is requested, but they must be at least
 * twelve if NSUnicodeStringEncoding is requested. 
 */
- (BOOL) getCString: (char*)buffer
	  maxLength: (NSUInteger)maxLength
	   encoding: (NSStringEncoding)encoding
{
  if (0 == maxLength || 0 == buffer) return NO;
  if (encoding == NSUnicodeStringEncoding)
    {
      unsigned	length = [self length];

      if (maxLength > length * sizeof(unichar))
	{
	  unichar	*ptr = (unichar*)(void*)buffer;

	  maxLength = (maxLength - 1) / sizeof(unichar);
	  [self getCharacters: ptr
			range: NSMakeRange(0, maxLength)];
	  ptr[maxLength] = 0;
	  return YES;
	}
      return NO;
    }
  else
    {
      NSData	*d = [self dataUsingEncoding: encoding];
      unsigned	length = [d length];
      BOOL	result = (length < maxLength) ? YES : NO;

      if (d == nil)
        {
	  [NSException raise: NSCharacterConversionException
		      format: @"Can't convert to C string."];
	}
      if (length >= maxLength)
        {
          length = maxLength-1;
	}
      memcpy(buffer, [d bytes], length);
      buffer[length] = '\0';
      return result;
    }
}

/**
 * Deprecated ... do not use.<br />.
 * Use -getCString:maxLength:encoding: instead.
 */
- (void) getCString: (char*)buffer
	  maxLength: (NSUInteger)maxLength
	      range: (NSRange)aRange
     remainingRange: (NSRange*)leftoverRange
{
  NSString	*s;

  /* As this is a deprecated method, keep things simple (but inefficient)
   * by copying the receiver to a new instance of a base library built-in
   * class, and use the implementation provided by that class.
   * We need an autorelease to avoid a memory leak if there is an exception.
   */
  s = AUTORELEASE([(NSString*)defaultPlaceholderString initWithString: self]);
  [s getCString: buffer
      maxLength: maxLength
	  range: aRange
 remainingRange: leftoverRange];
}


// Getting Numeric Values

- (BOOL) boolValue
{
  unsigned	length = [self length];

  if (length > 0)
    {
      unsigned	index;
      SEL	sel = @selector(characterAtIndex:);
      unichar	(*imp)() = (unichar (*)())[self methodForSelector: sel];

      for (index = 0; index < length; index++)
	{
	  unichar	c = (*imp)(self, sel, index);

	  if (c > 'y')
	    {
	      break;
	    }
          if (strchr("123456789yYtT", c) != 0)
	    {
	      return YES;
	    }
	  if (!isspace(c) && c != '0' && c != '-' && c != '+')
	    {
	      break;
	    }
	}
    }
  return NO;
}

/**
 * Returns the string's content as a decimal.<br />
 * Undocumented feature of Aplle Foundation.
 */
- (NSDecimal) decimalValue
{
  NSDecimal     result;

  NSDecimalFromString(&result, self, nil);
  return result;
}

/**
 * Returns the string's content as a double.  Skips leading whitespace.<br />
 * Conversion is not localised (i.e. uses '.' as the decimal separator).<br />
 * Returns 0.0 on underflow or if the string does not contain a number.
 */
- (double) doubleValue
{
  double	d = 0.0;
  [NSScanner _scanDouble: &d from: self];
  return d;
}

/**
 * Returns the string's content as a float.  Skips leading whitespace.<br />
 * Conversion is not localised (i.e. uses '.' as the decimal separator).<br />
 * Returns 0.0 on underflow or if the string does not contain a number.
 */
- (float) floatValue
{
  double	d = 0.0;
  [NSScanner _scanDouble: &d from: self];
  return (float)d;
}

/**
 * <p>Returns the string's content as an int.<br/>
 * Current implementation uses a C runtime library function, which does not
 * detect conversion errors -- use with care!</p>
 */
- (int) intValue
{
  const char *ptr = [self UTF8String];

  while (isspace(*ptr))
    {
      ptr++;
    }
  if ('-' == *ptr)
    {
      return (int)atoi(ptr);
    }
  else
    {
      uint64_t v;

      v = strtoul(ptr, 0, 10);
      return (int)v;
    } 
}

- (NSInteger) integerValue
{
  const char *ptr = [self UTF8String];

  while (isspace(*ptr))
    {
      ptr++;
    }
  if ('-' == *ptr)
    {
      return (NSInteger)atoll(ptr);
    }
  else
    {
      uint64_t  v;

      v = (uint64_t)strtoull(ptr, 0, 10);
      return (NSInteger)v;
    } 
}

- (long long) longLongValue
{
  const char *ptr = [self UTF8String];

  while (isspace(*ptr))
    {
      ptr++;
    }
  if ('-' == *ptr)
    {
      return atoll(ptr);
    }
  else
    {
      unsigned long long l;

      l = strtoull(ptr, 0, 10);
      return (long long)l;
    } 
}

// Working With Encodings

/**
 * <p>
 *   Returns the encoding used for any method accepting a C string.
 *   This value is determined automatically from the program's
 *   environment and cannot be changed programmatically.
 * </p>
 * <p>
 *   You should <em>NOT</em> override this method in an attempt to
 *   change the encoding being used... it won't work.
 * </p>
 * <p>
 *   In GNUstep, this encoding is determined by the initial value
 *   of the <code>GNUSTEP_STRING_ENCODING</code> environment
 *   variable.  If this is not defined,
 *   <code>NSISOLatin1StringEncoding</code> is assumed.
 * </p>
 */
+ (NSStringEncoding) defaultCStringEncoding
{
  return _DefaultStringEncoding;
}

/**
 * Returns an array of all available string encodings,
 * terminated by a null value.
 */
+ (NSStringEncoding*) availableStringEncodings
{
  return GSPrivateAvailableEncodings();
}

/**
 * Returns the localized name of the encoding specified.
 */
+ (NSString*) localizedNameOfStringEncoding: (NSStringEncoding)encoding
{
  id ourbundle;
  id ourname;

/*
      Should be path to localizable.strings file.
      Until we have it, just make sure that bundle
      is initialized.
*/
  ourbundle = [NSBundle bundleForLibrary: @"gnustep-base"];

  ourname = GSPrivateEncodingName(encoding);
  return [ourbundle localizedStringForKey: ourname
				    value: ourname
				    table: nil];
}

/**
 *  Returns whether this string can be converted to the given string encoding
 *  without information loss.
 */
- (BOOL) canBeConvertedToEncoding: (NSStringEncoding)encoding
{
  id d = [self dataUsingEncoding: encoding allowLossyConversion: NO];

  return d != nil ? YES : NO;
}

/**
 *  Converts string to a byte array in the given encoding, returning nil if
 *  this would result in information loss.
 */
- (NSData*) dataUsingEncoding: (NSStringEncoding)encoding
{
  return [self dataUsingEncoding: encoding allowLossyConversion: NO];
}

/**
 *  Converts string to a byte array in the given encoding.  If flag is NO,
 *  nil would be returned if this would result in information loss.
 */
- (NSData*) dataUsingEncoding: (NSStringEncoding)encoding
	 allowLossyConversion: (BOOL)flag
{
  unsigned	len = [self length];
  NSData	*d;

  if (NSUnicodeStringEncoding == encoding)
    {
      unichar	*u;
      unsigned	l;

      /* Fast path for Unicode (UTF16) without a specific byte order,
       * where we must prepend a byte order mark.
       * The case for UTF32 is handled in the slower branch.
       */
      u = (unichar*)NSZoneMalloc(NSDefaultMallocZone(),
	(len + 1) * sizeof(unichar));
      *u = byteOrderMark;
      [self getCharacters: u + 1];
      l = GSUnicode(u, len, 0, 0);
      d = [NSDataClass dataWithBytesNoCopy: u
				    length: (l + 1) * sizeof(unichar)];
    }
  else
    {
      unichar		buf[8192];
      unichar		*u = buf;
      unsigned int	options;
      unsigned char	*b = 0;
      unsigned int	l = 0;

      /* Build a fake object on the stack and copy unicode characters
       * into its buffer from the receiver.
       * We can then use our concrete subclass implementation to do the
       * work of converting to the desired encoding.
       */
      if (NSUTF32StringEncoding == encoding)
	{
	  /* For UTF32 without byte order specified, we must include a
	   * BOM at the start of the data.
	   */
	  len++;
	  if (len >= 4096)
	    {
	      u = NSZoneMalloc(NSDefaultMallocZone(), len * sizeof(unichar));
	    }
	  *u = byteOrderMark;
	  [self getCharacters: u+1];
	}
      else
	{
	  if (len >= 4096)
	    {
	      u = NSZoneMalloc(NSDefaultMallocZone(), len * sizeof(unichar));
	    }
	  [self getCharacters: u];
	}

      if (flag == NO)
        {
	  options = GSUniStrict;
	}
      else
        {
	  options = 0;
	}
      if (GSFromUnicode(&b, &l, u, len, encoding, NSDefaultMallocZone(),
	options) == YES)
	{
	  d = [NSDataClass dataWithBytesNoCopy: b length: l];
	}
      else
        {
	  d = nil;
	}
      if (u != buf)
	{
	  NSZoneFree(NSDefaultMallocZone(), u);
	}
    }
  return d;
}

/**
 * Returns the encoding with which this string can be converted without
 * information loss that would result in most efficient character access.
 */
- (NSStringEncoding) fastestEncoding
{
  return NSUnicodeStringEncoding;
}

/**
 * Returns the smallest encoding with which this string can be converted
 * without information loss.
 */
- (NSStringEncoding) smallestEncoding
{
  return NSUnicodeStringEncoding;
}

- (NSUInteger) completePathIntoString: (NSString**)outputName
                        caseSensitive: (BOOL)flag
                     matchesIntoArray: (NSArray**)outputArray
                          filterTypes: (NSArray*)filterTypes
{
  NSString		*basePath = [self stringByDeletingLastPathComponent];
  NSString		*lastComp = [self lastPathComponent];
  NSString		*tmpPath;
  NSDirectoryEnumerator *e;
  NSMutableArray	*op = nil;
  unsigned		matchCount = 0;

  if (outputArray != 0)
    {
      op = (NSMutableArray*)[NSMutableArray array];
    }

  if (outputName != NULL)
    {
      *outputName = nil;
    }

  if ([basePath length] == 0)
    {
      basePath = @".";
    }

  e = [[NSFileManager defaultManager] enumeratorAtPath: basePath];
  while (tmpPath = [e nextObject], tmpPath)
    {
      /* Prefix matching */
      if (flag == YES)
	{ /* Case sensitive */
	  if ([tmpPath hasPrefix: lastComp] == NO)
	    {
	      continue;
	    }
	}
      else if ([[tmpPath uppercaseString]
	hasPrefix: [lastComp uppercaseString]] == NO)
	{
	  continue;
	}

      /* Extensions filtering */
      if (filterTypes
	&& ([filterTypes containsObject: [tmpPath pathExtension]] == NO))
	{
	  continue;
	}

      /* Found a completion */
      matchCount++;
      if (outputArray != NULL)
	{
	  [op addObject: tmpPath];
	}

      if ((outputName != NULL) &&
	((*outputName == nil) || (([*outputName length] < [tmpPath length]))))
	{
	  *outputName = tmpPath;
	}
    }
  if (outputArray != NULL)
    {
      *outputArray = AUTORELEASE([op copy]);
    }
  return matchCount;
}

static NSFileManager *fm = nil;

#if	defined(_WIN32)
- (const GSNativeChar*) fileSystemRepresentation
{
  if (fm == nil)
    {
      fm = RETAIN([NSFileManager defaultManager]);
    }
  return [fm fileSystemRepresentationWithPath: self];
}

- (BOOL) getFileSystemRepresentation: (GSNativeChar*)buffer
			   maxLength: (NSUInteger)size
{
  const unichar	*ptr;
  unsigned	i;

  if (size == 0)
    {
      return NO;
    }
  if (buffer == 0)
    {
      [NSException raise: NSInvalidArgumentException
		  format: @"%@ given null pointer",
	NSStringFromSelector(_cmd)];
    }
  ptr = [self fileSystemRepresentation];
  for (i = 0; i < size; i++)
    {
      buffer[i] = ptr[i];
      if (ptr[i] == 0)
	{
	  break;
	}
    }
  if (i == size && ptr[i] != 0)
    {
      return NO;	// Not at end.
    }
  return YES;
}
#else
- (const GSNativeChar*) fileSystemRepresentation
{
  if (fm == nil)
    {
      fm = RETAIN([NSFileManager defaultManager]);
    }
  return [fm fileSystemRepresentationWithPath: self];
}

- (BOOL) getFileSystemRepresentation: (GSNativeChar*)buffer
			   maxLength: (NSUInteger)size
{
  const char* ptr;

  if (size == 0)
    {
      return NO;
    }
  if (buffer == 0)
    {
      [NSException raise: NSInvalidArgumentException
		  format: @"%@ given null pointer",
	NSStringFromSelector(_cmd)];
    }
  ptr = [self fileSystemRepresentation];
  if (strlen(ptr) > size)
    {
      return NO;
    }
  strncpy(buffer, ptr, size);
  return YES;
}
#endif

- (NSString*) lastPathComponent
{
  unsigned int	l = [self length];
  NSRange	range;
  unsigned int	i;

  if (l == 0)
    {
      return @"";		// self is empty
    }

  // Skip back over any trailing path separators, but not in to root.
  i = rootOf(self, l);
  while (l > i && pathSepMember([self characterAtIndex: l-1]) == YES)
    {
      l--;
    }

  // If only the root is left, return it.
  if (i == l)
    {
      /*
       * NB. tilde escapes should not have trailing separator in the
       * path component as they are not trreated as true roots.
       */
      if ([self characterAtIndex: 0] == '~'
	&& pathSepMember([self characterAtIndex: i-1]) == YES)
	{
	  return [self substringToIndex: i-1];
	}
      return [self substringToIndex: i];
    }

  // Got more than root ... find last component.
  range = [self rangeOfCharacterFromSet: pathSeps()
				options: NSBackwardsSearch
				  range: ((NSRange){i, l-i})];
  if (range.length > 0)
    {
      // Found separator ... adjust to point to component.
      i = NSMaxRange(range);
    }
  return [self substringWithRange: ((NSRange){i, l-i})];
}

- (NSRange) paragraphRangeForRange: (NSRange)range
{
  NSUInteger startIndex;
  NSUInteger endIndex;

  [self getParagraphStart: &startIndex
        end: &endIndex
        contentsEnd: NULL
        forRange: range];
  return NSMakeRange(startIndex, endIndex - startIndex);
}

- (NSString*) pathExtension
{
  NSRange	range;
  unsigned int	l = [self length];
  unsigned int	root;

  if (l == 0)
    {
      return @"";
    }
  root = rootOf(self, l);

  /*
   * Step past trailing path separators.
   */
  while (l > root && pathSepMember([self characterAtIndex: l-1]) == YES)
    {
      l--;
    }
  range = NSMakeRange(root, l-root);

  /*
   * Look for a dot in the path ... if there isn't one, or if it is
   * immediately after the root or a path separator, there is no extension.
   */
  range = [self rangeOfString: @"."
                      options: NSBackwardsSearch
                        range: range
                       locale: nil];
  if (range.length > 0 && range.location > root
    && pathSepMember([self characterAtIndex: range.location-1]) == NO)
    {
      NSRange	sepRange;

      /*
       * Found a dot, so we determine the range of the (possible)
       * path extension, then check to see if we have a path
       * separator within it ... if we have a path separator then
       * the dot is inside the last path component and there is
       * therefore no extension.
       */
      range.location++;
      range.length = l - range.location;
      sepRange = [self rangeOfCharacterFromSet: pathSeps()
				       options: NSBackwardsSearch
				         range: range];
      if (sepRange.length == 0)
	{
	  return [self substringFromRange: range];
	}
    }

  return @"";
}

- (NSString *) precomposedStringWithCompatibilityMapping
{
#if (GS_USE_ICU == 1) && defined(HAVE_UNICODE_UNORM2_H)
  return [self _normalizedICUStringOfType: "nfkc" mode: UNORM2_COMPOSE];
#else
  return [self notImplemented: _cmd];
#endif
}
 
- (NSString *) precomposedStringWithCanonicalMapping
{
#if (GS_USE_ICU == 1) && defined(HAVE_UNICODE_UNORM2_H)
   return [self _normalizedICUStringOfType: "nfc" mode: UNORM2_COMPOSE];
#else
  return [self notImplemented: _cmd];
#endif
}
 
- (NSString*) stringByAppendingPathComponent: (NSString*)aString
{
  unsigned	originalLength = [self length];
  unsigned	length = originalLength;
  unsigned	aLength = [aString length];
  unsigned	root;
  unichar	buf[length+aLength+1];

  root = rootOf(aString, aLength);

  if (length == 0)
    {
      [aString getCharacters: buf range: ((NSRange){0, aLength})];
      length = aLength;
      root = rootOf(aString, aLength);
    }
  else
    {
      /* If the 'component' has a leading path separator (or drive spec
       * in windows) then we need to find its length so we can strip it.
       */
      if (root > 0)
	{
	  unichar c = [aString characterAtIndex: 0];

	  if (c == '~')
	    {
	      root = 0;
	    }
	  else if (root > 1 && pathSepMember(c))
	    {
	      int	i;

	      for (i = 1; i < root; i++)
		{
		  c = [aString characterAtIndex: i];
		  if (!pathSepMember(c))
		    {
		      break;
		    }
		}
	      root = i;
	    }
	}

      [self getCharacters: buf range: ((NSRange){0, length})];

      /* We strip back trailing path separators, and replace them with
       * a single one ... except in the case where we have a windows
       * drive specification, and the string being appended does not
       * have a path separator as a root. In that case we just want to
       * append to the drive specification directly, leaving a relative
       * path like c:foo
       */
      if (length != 2 || buf[1] != ':' || GSPathHandlingUnix() == YES
	|| buf[0] < 'A' || buf[0] > 'z' || (buf[0] > 'Z' && buf[0] < 'a')
	|| (root > 0 && pathSepMember([aString characterAtIndex: root-1])))
	{
	  while (length > 0 && pathSepMember(buf[length-1]) == YES)
	    {
	      length--;
	    }
	  buf[length++] = pathSepChar();
	}

      if ((aLength - root) > 0)
	{
	  // appending .. discard root from aString
	  [aString getCharacters: &buf[length]
			   range: ((NSRange){root, aLength-root})];
	  length += aLength-root;
	}
      // Find length of root part of new path.
      root = rootOf(self, originalLength);
    }

  if (length > 0)
    {
      /* Trim trailing path separators as long as they are not part of
       * the root. 
       */
      aLength = length - 1;
      while (aLength > root && pathSepMember(buf[aLength]) == YES)
	{
	  aLength--;
	  length--;
	}

      /* Trim multi separator sequences outside root (root may contain an
       * initial // pair if it is a windows UNC path).
       */
      if (length > 0)
	{
	  while (aLength > root)
	    {
	      if (pathSepMember(buf[aLength]) == YES)
		{
		  buf[aLength] = pathSepChar();
		  if (pathSepMember(buf[aLength-1]) == YES)
		    {
		      unsigned	pos;

		      buf[aLength-1] = pathSepChar();
		      for (pos = aLength+1; pos < length; pos++)
			{
			  buf[pos-1] = buf[pos];
			}
		      length--;
		    }
		}
	      aLength--;
	    }
	}
    }
  return [NSStringClass stringWithCharacters: buf length: length];
}

- (NSString*) stringByAppendingPathExtension: (NSString*)aString
{
  unsigned	l = [self length];
  unsigned 	originalLength = l;
  unsigned	root;

  if (l == 0)
    {
      NSLog(@"[%@-%@] cannot append extension '%@' to empty string",
	NSStringFromClass([self class]), NSStringFromSelector(_cmd), aString);
      return @"";		// Must have a file name to append extension.
    }
  root = rootOf(self, l);
  /*
   * Step past trailing path separators.
   */
  while (l > root && pathSepMember([self characterAtIndex: l-1]) == YES)
    {
      l--;
    }
  if (root == l)
    {
      NSLog(@"[%@-%@] cannot append extension '%@' to path '%@'",
	NSStringFromClass([self class]), NSStringFromSelector(_cmd),
	aString, self);
      return IMMUTABLE(self);	// Must have a file name to append extension.
    }

  /* MacOS-X prohibits an extension beginning with a path separator,
   * but this code extends that a little to prohibit any root except
   * one beginning with '~' from being used as an extension. 
   */ 
  root = rootOf(aString, [aString length]);
  if (root > 0 && [aString characterAtIndex: 0] != '~')
    {
      NSLog(@"[%@-%@] cannot append extension '%@' to path '%@'",
	NSStringFromClass([self class]), NSStringFromSelector(_cmd),
	aString, self);
      return IMMUTABLE(self);	// Must have a file name to append extension.
    }

  if (originalLength != l)
    {
      NSRange	range = NSMakeRange(0, l);

      return [[self substringFromRange: range]
	stringByAppendingFormat: @".%@", aString];
    }
  return [self stringByAppendingFormat: @".%@", aString];
}

- (NSString*) stringByDeletingLastPathComponent
{
  unsigned int	length;
  unsigned int	root;
  unsigned int	end;
  unsigned int	i;

  end = length = [self length];
  if (length == 0)
    {
      return @"";
    }
  i = root = rootOf(self, length);

  /*
   * Any root without a trailing path separator can be deleted
   * as it's either a relative path or a tilde expression.
   */
  if (i == length && pathSepMember([self characterAtIndex: i-1]) == NO)
    {
      return @"";	// Delete relative root
    }

  /*
   * Step past trailing path separators.
   */
  while (end > i && pathSepMember([self characterAtIndex: end-1]) == YES)
    {
      end--;
    }

  /*
   * If all we have left is the root, return that root, except for the
   * special case of a tilde expression ... which may be deleted even
   * when it is followed by a separator.
   */
  if (end == i)
    {
      if ([self characterAtIndex: 0] == '~')
	{
	  return @"";				// Tilde roots may be deleted.
	}
      return [self substringToIndex: i];	// Return root component.
    }
  else
    {
      NSString	*result;
      unichar	*to;
      unsigned	o;
      unsigned	lastComponent = root;
      GS_BEGINITEMBUF(from, (end * 2 * sizeof(unichar)), unichar)

      to = from + end;
      [self getCharacters: from range: NSMakeRange(0, end)];
      for (o = 0; o < root; o++)
	{
	  to[o] = from[o];
	}
      for (i = root; i < end; i++)
	{
	  if (pathSepMember(from[i]))
	    {
	      if (o > lastComponent)
		{
		  to[o++] = from[i];
		  lastComponent = o;
		}
	    }
	  else
	    {
	      to[o++] = from[i];
	    }
	}
      if (lastComponent > root)
	{
	  o = lastComponent - 1;
	}
      else
	{
	  o = root;
	}
      result = [NSString stringWithCharacters: to length: o];
      GS_ENDITEMBUF();
      return result;
    }
}

- (NSString*) stringByDeletingPathExtension
{
  NSRange	range;
  NSRange	r0;
  NSRange	r1;
  NSString	*substring;
  unsigned	l = [self length];
  unsigned	root;

  if ((root = rootOf(self, l)) == l)
    {
      return IMMUTABLE(self);
    }

  /*
   * Skip past any trailing path separators... but not into root.
   */
  while (l > root && pathSepMember([self characterAtIndex: l-1]) == YES)
    {
      l--;
    }
  range = NSMakeRange(root, l-root);
  /*
   * Locate path extension.
   */
  r0 = [self rangeOfString: @"."
		   options: NSBackwardsSearch
		     range: range
                    locale: nil];
  /*
   * Locate a path separator.
   */
  r1 = [self rangeOfCharacterFromSet: pathSeps()
			     options: NSBackwardsSearch
			       range: range];
  /*
   * Assuming the extension separator was found in the last path
   * component, set the length of the substring we want.
   */
  if (r0.length > 0 && r0.location > root
    && (r1.length == 0 || r1.location < r0.location))
    {
      l = r0.location;
    }
  substring = [self substringToIndex: l];
  return substring;
}

- (NSString*) stringByExpandingTildeInPath
{
  NSString	*homedir;
  NSRange	firstSlashRange;
  unsigned	length;

  if ((length = [self length]) == 0)
    {
      return IMMUTABLE(self);
    }
  if ([self characterAtIndex: 0] != 0x007E)
    {
      return IMMUTABLE(self);
    }

  /* FIXME ... should remove in future
   * Anything beginning '~@' is assumed to be a windows path specification
   * which can't be expanded.
   */
  if (length > 1 && [self characterAtIndex: 1] == 0x0040)
    {
      return IMMUTABLE(self);
    }

  firstSlashRange = [self rangeOfCharacterFromSet: pathSeps()
                                          options: NSLiteralSearch
                                            range: ((NSRange){0, length})];
  if (firstSlashRange.length == 0)
    {
      firstSlashRange.location = length;
    }

  /* FIXME ... should remove in future
   * Anything beginning '~' followed by a single letter is assumed
   * to be a windows drive specification.
   */
  if (firstSlashRange.location == 2 && isalpha([self characterAtIndex: 1]))
    {
      return IMMUTABLE(self);
    }

  if (firstSlashRange.location != 1)
    {
      /* It is of the form `~username/blah/...' or '~username' */
      int	userNameLen;
      NSString	*uname;

      if (firstSlashRange.length != 0)
	{
	  userNameLen = firstSlashRange.location - 1;
	}
      else
	{
	  /* It is actually of the form `~username' */
	  userNameLen = [self length] - 1;
	  firstSlashRange.location = [self length];
	}
      uname = [self substringWithRange: ((NSRange){1, userNameLen})];
      homedir = NSHomeDirectoryForUser(uname);
    }
  else
    {
      /* It is of the form `~/blah/...' or is '~' */
      homedir = NSHomeDirectory();
    }

  if (homedir != nil)
    {
      if (firstSlashRange.location < length)
	{
	  return [homedir stringByAppendingPathComponent:
	    [self substringFromIndex: firstSlashRange.location]];
	}
      else
	{
	  return IMMUTABLE(homedir);
	}
    }
  else
    {
      return IMMUTABLE(self);
    }
}

- (NSString*) stringByAbbreviatingWithTildeInPath
{
  NSString	*homedir;

  if (YES == [self hasPrefix: @"~"])
    {
      return IMMUTABLE(self);
    }
  homedir = NSHomeDirectory();
  if (NO == [self hasPrefix: homedir])
    {
      /* OSX compatibility ... we clean up the path to try to get a
       * home directory we can abbreviate.
       */
      self = [self stringByStandardizingPath];
      if (NO == [self hasPrefix: homedir])
        {
          return IMMUTABLE(self);
        }
    }
  if ([self length] == [homedir length])
    {
      return @"~";
    }
  return [@"~" stringByAppendingPathComponent:
    [self substringFromIndex: [homedir length]]];
}

/**
 * Returns a string formed by extending or truncating the receiver to
 * newLength characters.  If the new string is larger, it is padded
 * by appending characters from padString (appending it as many times
 * as required).  The first character from padString to be appended
 * is specified by padIndex.<br />
 */
- (NSString*) stringByPaddingToLength: (NSUInteger)newLength
			   withString: (NSString*)padString
		      startingAtIndex: (NSUInteger)padIndex
{
  unsigned	length = [self length];
  unsigned	padLength;

  if (padString == nil || [padString isKindOfClass: [NSString class]] == NO)
    {
      [NSException raise: NSInvalidArgumentException
	format: @"%@ - Illegal pad string", NSStringFromSelector(_cmd)];
    }
  padLength = [padString length];
  if (padIndex >= padLength)
    {
      [NSException raise: NSRangeException
	format: @"%@ - pad index larger too big", NSStringFromSelector(_cmd)];
    }
  if (newLength == length)
    {
      return IMMUTABLE(self);
    }
  else if (newLength < length)
    {
      return [self substringToIndex: newLength];
    }
  else
    {
      length = newLength - length;	// What we want to add.
      if (length <= (padLength - padIndex))
	{
	  NSRange	r;

	  r = NSMakeRange(padIndex, length);
	  return [self stringByAppendingString:
	    [padString substringWithRange: r]];
	}
      else
	{
	  NSMutableString	*m = [self mutableCopy];

	  if (padIndex > 0)
	    {
	      NSRange	r;

	      r = NSMakeRange(padIndex, padLength - padIndex);
	      [m appendString: [padString substringWithRange: r]];
	      length -= r.length;
	    }
	  /*
	   * In case we have to append a small string lots of times,
	   * we cache the method impllementation to do it.
	   */
	  if (length >= padLength)
	    {
	      void	(*appImp)(NSMutableString*, SEL, NSString*);
	      SEL	appSel;

	      appSel = @selector(appendString:);
	      appImp = (void (*)(NSMutableString*, SEL, NSString*))
		[m methodForSelector: appSel];
	      while (length >= padLength)
		{
		  (*appImp)(m, appSel, padString);
		  length -= padLength;
		}
	    }
	  if (length > 0)
	    {
	      [m appendString:
		[padString substringWithRange: NSMakeRange(0, length)]];
	    }
	  return AUTORELEASE(m);
	}
    }
}

/**
 * Returns a string created by replacing percent escape sequences in the
 * receiver assuming that the resulting data represents characters in
 * the specified encoding.<br />
 * Returns nil if the result is not a string in the specified encoding.
 */
- (NSString*) stringByReplacingPercentEscapesUsingEncoding: (NSStringEncoding)e
{
  NSMutableData	*d;
  NSString	*s = nil;

  d = [[self dataUsingEncoding: NSASCIIStringEncoding] mutableCopy];
  if (d != nil)
    {
      unsigned char	*p = (unsigned char*)[d mutableBytes];
      unsigned		l = [d length];
      unsigned		i = 0;
      unsigned		j = 0;

      while (i < l)
	{
	  unsigned char	t;

	  if ((t = p[i++]) == '%')
	    {
	      unsigned char	c;

	      if (i >= l)
		{
		  DESTROY(d);
		  break;
		}
	      t = p[i++];

	      if (isxdigit(t))
		{
		  if (t <= '9')
		    {
		      c = t - '0';
		    }
		  else if (t <= 'F')
		    {
		      c = t - 'A' + 10;
		    }
		  else
		    {
		      c = t - 'a' + 10;
		    }
		}
	      else
		{
		  DESTROY(d);
		  break;
		}
	      c <<= 4;

	      if (i >= l)
		{
		  DESTROY(d);
		  break;
		}
	      t = p[i++];
	      if (isxdigit(t))
		{
		  if (t <= '9')
		    {
		      c |= t - '0';
		    }
		  else if (t <= 'F')
		    {
		      c |= t - 'A' + 10;
		    }
		  else
		    {
		      c |= t - 'a' + 10;
		    }
		}
	      else
		{
		  DESTROY(d);
		  break;
		}
	      p[j++] = c;
	    }
	  else
	    {
	      p[j++] = t;
	    }
	}
      [d setLength: j];
      s = AUTORELEASE([[NSString alloc] initWithData: d encoding: e]);
      RELEASE(d);
    }
  return s;
}

- (NSString*) stringByResolvingSymlinksInPath
{
  NSString	*s = self;

  if (0 == [s length])
    {
      return @"";
    }
  if ('~' == [s characterAtIndex: 0])
    {
      s = [s stringByExpandingTildeInPath];
    }
#if defined(_WIN32)
  return IMMUTABLE(s);
#else

{
  #if defined(__GLIBC__) || defined(__FreeBSD__)
  #define GS_MAXSYMLINKS sysconf(_SC_SYMLOOP_MAX)
  #else
  #define GS_MAXSYMLINKS MAXSYMLINKS
  #endif
 
  #ifndef PATH_MAX
  #define PATH_MAX 1024
  /* Don't use realpath unless we know we have the correct path size limit */
  #ifdef        HAVE_REALPATH
  #undef        HAVE_REALPATH
  #endif
  #endif
  char		newBuf[PATH_MAX];
#ifdef HAVE_REALPATH

  if (realpath([s fileSystemRepresentation], newBuf) == 0)
    return IMMUTABLE(s);
#else
  char		extra[PATH_MAX];
  char		*dest;
  const char	*name = [s fileSystemRepresentation];
  const char	*start;
  const	char	*end;
  unsigned	num_links = 0;

  if (name[0] != '/')
    {
      if (!getcwd(newBuf, PATH_MAX))
	{
	  return IMMUTABLE(s);	/* Couldn't get directory.	*/
	}
      dest = strchr(newBuf, '\0');
    }
  else
    {
      newBuf[0] = '/';
      dest = &newBuf[1];
    }

  for (start = end = name; *start; start = end)
    {
      struct stat	st;
      int		n;
      int		len;

      /* Elide repeated path separators	*/
      while (*start == '/')
	{
	  start++;
	}
      /* Locate end of path component	*/
      end = start;
      while (*end && *end != '/')
	{
	  end++;
	}
      len = end - start;
      if (len == 0)
	{
	  break;	/* End of path.	*/
	}
      else if (len == 1 && *start == '.')
	{
          /* Elide '/./' sequence by ignoring it.	*/
	}
      else if (len == 2 && strncmp(start, "..", len) == 0)
	{
	  /*
	   * Backup - if we are not at the root, remove the last component.
	   */
	  if (dest > &newBuf[1])
	    {
	      do
		{
		  dest--;
		}
	      while (dest[-1] != '/');
	    }
	}
      else
        {
          if (dest[-1] != '/')
	    {
	      *dest++ = '/';
	    }
          if (&dest[len] >= &newBuf[PATH_MAX])
	    {
	      return IMMUTABLE(s);	/* Resolved name too long.	*/
	    }
          memmove(dest, start, len);
          dest += len;
          *dest = '\0';

          if (lstat(newBuf, &st) < 0)
	    {
	      return IMMUTABLE(s);	/* Unable to stat file.		*/
	    }
          if (S_ISLNK(st.st_mode))
            {
              char	buf[PATH_MAX];
	      int	l;

              if (++num_links > GS_MAXSYMLINKS)
		{
		  return IMMUTABLE(s);	/* Too many links.	*/
		}
              n = readlink(newBuf, buf, PATH_MAX);
              if (n < 0)
		{
		  return IMMUTABLE(s);	/* Couldn't resolve.	*/
		}
              buf[n] = '\0';

	      l = strlen(end);
              if ((n + l) >= PATH_MAX)
		{
		  return IMMUTABLE(s);	/* Path too long.	*/
		}
	      /*
	       * Concatenate the resolved name with the string still to
	       * be processed, and start using the result as input.
	       */
              memcpy(buf + n, end, l);
	      n += l;
	      buf[n] = '\0';
              memcpy(extra, buf, n);
	      extra[n] = '\0';
              name = end = extra;

              if (buf[0] == '/')
		{
		  /*
		   * For an absolute link, we start at root again.
		   */
		  dest = newBuf + 1;
		}
              else
		{
		  /*
		   * Backup - remove the last component.
		   */
		  if (dest > newBuf + 1)
		    {
		      do
			{
			  dest--;
			}
		      while (dest[-1] != '/');
		    }
		}
            }
          else
	    {
	      num_links = 0;
	    }
        }
    }
  if (dest > newBuf + 1 && dest[-1] == '/')
    {
      --dest;
    }
  *dest = '\0';
#endif
  if (strncmp(newBuf, "/private/", 9) == 0)
    {
      struct stat	st;

      if (lstat(&newBuf[8], &st) == 0)
	{
	  int	l = strlen(newBuf) - 7;

	  memmove(newBuf, &newBuf[8], l);
	}
    }
  return [[NSFileManager defaultManager]
   stringWithFileSystemRepresentation: newBuf length: strlen(newBuf)];
}
#endif
}

- (NSString*) stringByStandardizingPath
{
  NSMutableString	*s;
  NSRange		r;
  unichar		(*caiImp)(NSString*, SEL, NSUInteger);
  unsigned int		l = [self length];
  unichar		c;
  unsigned		root;

  if (l == 0)
    {
      return @"";
    }
  c = [self characterAtIndex: 0];
  if (c == '~')
    {
      s = AUTORELEASE([[self stringByExpandingTildeInPath] mutableCopy]);
    }
  else
    {
      s = AUTORELEASE([self mutableCopy]);
    }

  /* We must always use the standard path separator unless specifically set
   * to use the mswindows one.  That ensures that standardised paths and
   * anything built by adding path components to them use a consistent
   * separator character anad can be compared readily using standard string
   * comparisons.
   */
  if (GSPathHandlingWindows() == YES)
    {
      [s replaceString: @"/" withString: @"\\"];
    }
  else
    {
      [s replaceString: @"\\" withString: @"/"];
    }

  l = [s length];
  root = rootOf(s, l);

  caiImp = (unichar (*)())[s methodForSelector: caiSel];

  /* Remove any separators ('/') immediately after the trailing
   * separator in the root (if any).
   */
  if (root > 0 && YES == pathSepMember((*caiImp)(s, caiSel, root-1)))
    {
      unsigned	i;

      for (i = root; i < l; i++)
	{
	  if (NO == pathSepMember((*caiImp)(s, caiSel, i)))
	    {
	      break;
	    }
	}
      if (i > root)
	{
	  r = (NSRange){root, i-root};
	  [s deleteCharactersInRange: r];
	  l -= r.length;
	}
    }

  /* Condense multiple separator ('/') sequences.
   */
  r = (NSRange){root, l-root};
  while ((r = [s rangeOfCharacterFromSet: pathSeps()
				 options: 0
				   range: r]).length == 1)
    {
      while (NSMaxRange(r) < l
	&& pathSepMember((*caiImp)(s, caiSel, NSMaxRange(r))) == YES)
	{
	  r.length++;
	}
      r.location++;
      r.length--;
      if (r.length > 0)
	{
	  [s deleteCharactersInRange: r];
	  l -= r.length;
	}
      r.length = l - r.location;
    }

  /* Remove trailing ('.') as long as it's preceeded by a path separator.
   * As a special case for OSX compatibility, we only remove the trailing
   * dot if it's not immediately after the root.
   */
  if (l > root + 1 && (*caiImp)(s, caiSel, l-1) == '.'
    && pathSepMember((*caiImp)(s, caiSel, l-2)) == YES)
    {
      l--;
      [s deleteCharactersInRange: NSMakeRange(l, 1)];
    }

  // Condense ('/./') sequences.
  r = (NSRange){root, l-root};
  while ((r = [s rangeOfString: @"." options: 0 range: r locale: nil]).length
    == 1)
    {
      if (r.location > 0 && r.location < l - 1
	&& pathSepMember((*caiImp)(s, caiSel, r.location-1)) == YES
	&& pathSepMember((*caiImp)(s, caiSel, r.location+1)) == YES)
	{
	  r.length++;
	  [s deleteCharactersInRange: r];
	  l -= r.length;
	}
      else
	{
	  r.location++;
	}
      r.length = l - r.location;
    }

  // Strip trailing '/' if present.
  if (l > root && pathSepMember([s characterAtIndex: l - 1]) == YES)
    {
      r.length = 1;
      r.location = l - r.length;
      [s deleteCharactersInRange: r];
      l -= r.length;
    }

  if ([s isAbsolutePath] == NO)
    {
      return s;
    }

  // Remove leading `/private' if present.
  if ([s hasPrefix: @"/private"])
    {
      [s deleteCharactersInRange: ((NSRange){0,8})];
      l -= 8;
    }

  /*
   *	For absolute paths, we must 
   *	remove '/../' sequences and their matching parent directories.
   */
  r = (NSRange){root, l-root};
  while ((r = [s rangeOfString: @".." options: 0 range: r locale: nil]).length
    == 2)
    {
      if (r.location > 0
	&& pathSepMember((*caiImp)(s, caiSel, r.location-1)) == YES
        && (NSMaxRange(r) == l
	  || pathSepMember((*caiImp)(s, caiSel, NSMaxRange(r))) == YES))
	{
	  BOOL	atEnd = (NSMaxRange(r) == l) ? YES : NO;

	  if (r.location > root)
	    {
	      NSRange r2;

	      r.location--;
	      r.length++;
	      r2 = NSMakeRange(root, r.location-root);
	      r = [s rangeOfCharacterFromSet: pathSeps()
				     options: NSBackwardsSearch
				       range: r2];
	      if (r.length == 0)
		{
		  r = r2;	// Location just after root
		  r.length++;
		}
	      else
		{
		  r.length = NSMaxRange(r2) - r.location;
	          r.location++;		// Location Just after last separator
		}
	      r.length += 2;		// Add the `..' 
	    }
	  if (NO == atEnd)
	    {
	      r.length++;		// Add the '/' after the '..'
	    }
	  [s deleteCharactersInRange: r];
	  l -= r.length;
	}
      else
	{
	  r.location++;
	}
      r.length = l - r.location;
    }

  return IMMUTABLE(s);
}

/**
 * Return a string formed by removing characters from the ends of the
 * receiver.  Characters are removed only if they are in aSet.<br />
 * If the string consists entirely of characters in aSet, an empty
 * string is returned.<br />
 * The aSet argument must not be nil.<br />
 */
- (NSString*) stringByTrimmingCharactersInSet: (NSCharacterSet*)aSet
{
  unsigned	length = [self length];
  unsigned	end = length;
  unsigned	start = 0;

  if (aSet == nil)
    {
      [NSException raise: NSInvalidArgumentException
	format: @"%@ - nil character set argument", NSStringFromSelector(_cmd)];
    }
  if (length > 0)
    {
      unichar	(*caiImp)(NSString*, SEL, NSUInteger);
      BOOL	(*mImp)(id, SEL, unichar);
      unichar	letter;

      caiImp = (unichar (*)())[self methodForSelector: caiSel];
      mImp = (BOOL(*)(id,SEL,unichar)) [aSet methodForSelector: cMemberSel];

      while (end > 0)
	{
	  letter = (*caiImp)(self, caiSel, end-1);
	  if ((*mImp)(aSet, cMemberSel, letter) == NO)
	    {
	      break;
	    }
	  end--;
	}
      while (start < end)
	{
	  letter = (*caiImp)(self, caiSel, start);
	  if ((*mImp)(aSet, cMemberSel, letter) == NO)
	    {
	      break;
	    }
	  start++;
	}
    }
  if (start == 0 && end == length)
    {
      return IMMUTABLE(self);
    }
  if (start == end)
    {
      return @"";
    }
  return [self substringFromRange: NSMakeRange(start, end - start)];
}

// private methods for Unicode level 3 implementation
- (int) _baseLength
{
  int		blen = 0;
  unsigned	len = [self length];

  if (len > 0)
    {
      unsigned int	count = 0;
      unichar	(*caiImp)(NSString*, SEL, NSUInteger);

      caiImp = (unichar (*)())[self methodForSelector: caiSel];
      while (count < len)
	{
	  if (!uni_isnonsp((*caiImp)(self, caiSel, count++)))
	    {
	      blen++;
	    }
	}
    }
  return blen;
}

+ (NSString*) pathWithComponents: (NSArray*)components
{
  NSString	*s;
  unsigned	c;
  unsigned	i;

  c = [components count];
  if (c == 0)
    {
      return @"";
    }
  s = [components objectAtIndex: 0];
  if ([s length] == 0)
    {
      s = pathSepString();
    }
  for (i = 1; i < c; i++)
    {
      s = [s stringByAppendingPathComponent: [components objectAtIndex: i]];
    }
  return s;
}

- (BOOL) isAbsolutePath
{
  unichar	c;
  unsigned	l = [self length];
  unsigned	root;

  if (l == 0)
    {
      return NO;		// Empty string ... relative
    }
  c = [self characterAtIndex: 0];
  if (c == (unichar)'~')
    {
      return YES;		// Begins with tilde ... absolute
    }

  /*
   * Any string beginning with '/' is absolute ... except in windows mode
   * or on windows and not in unix mode.
   */
  if (c == pathSepChar())
    {
#if defined(_WIN32)
      if (GSPathHandlingUnix() == YES)
	{
	  return YES;
	}
#else
      if (GSPathHandlingWindows() == NO)
	{
	  return YES;
	}
#endif
     }

  /*
   * Any root over two characters long must be a drive specification with a
   * slash (absolute) or a UNC path (always absolute).
   */
  root = rootOf(self, l);
  if (root > 2)
    {
      return YES;		// UNC or C:/ ... absolute
    }

  /*
   * What we have left are roots of the form 'C:' or '\' or a path
   * with no root, or a '/' (in windows mode only sence we already
   * handled a single slash in unix mode) ...
   * all these cases are relative paths.
   */
  return NO;
}

- (NSArray*) pathComponents
{
  NSMutableArray	*a;
  NSArray		*r;
  NSString		*s = self;
  unsigned int		l = [s length];
  unsigned int		root;
  unsigned int		i;
  NSRange		range;

  if (l == 0)
    {
      return [NSArray array];
    }
  root = rootOf(s, l);
  a = [[NSMutableArray alloc] initWithCapacity: 8];
  if (root > 0)
    {
      [a addObject: [s substringToIndex: root]];
    }
  i = root;

  while (i < l)
    {
      range = [s rangeOfCharacterFromSet: pathSeps()
				 options: NSLiteralSearch
				   range: ((NSRange){i, l - i})];
      if (range.length > 0)
	{
	  if (range.location > i)
	    {
	      [a addObject: [s substringWithRange:
		NSMakeRange(i, range.location - i)]];
	    }
	  i = NSMaxRange(range);
	}
      else
	{
	  [a addObject: [s substringFromIndex: i]];
	  i = l;
	}
    }

  /*
   * If the path ended with a path separator which was not already
   * added as part of the root, add it as final component.
   */
  if (l > root && pathSepMember([s characterAtIndex: l-1]))
    {
      [a addObject: pathSepString()];
    }

  r = [a copy];
  RELEASE(a);
  return AUTORELEASE(r);
}

- (NSArray*) stringsByAppendingPaths: (NSArray*)paths
{
  NSMutableArray	*a;
  NSArray		*r;
  unsigned		i, count = [paths count];

  a = [[NSMutableArray allocWithZone: NSDefaultMallocZone()]
	initWithCapacity: count];
  for (i = 0; i < count; i++)
    {
      NSString	*s = [paths objectAtIndex: i];

      s = [self stringByAppendingPathComponent: s];
      [a addObject: s];
    }
  r = [a copy];
  RELEASE(a);
  return AUTORELEASE(r);
}

/**
 * Returns an autoreleased string with given format using the default locale.
 */
+ (NSString*) localizedStringWithFormat: (NSString*) format, ...
{
  va_list ap;
  id ret;

  va_start(ap, format);
  if (format == nil)
    {
      ret = nil;
    }
  else
    {
      ret = AUTORELEASE([[self allocWithZone: NSDefaultMallocZone()]
        initWithFormat: format locale: GSPrivateDefaultLocale() arguments: ap]);
    }
  va_end(ap);
  return ret;
}

/**
 * Compares this string with aString ignoring case.  Convenience for
 * -compare:options:range: with the <code>NSCaseInsensitiveSearch</code>
 * option, in the default locale.
 */
- (NSComparisonResult) caseInsensitiveCompare: (NSString*)aString
{
  if (aString == self) return NSOrderedSame;
  return [self compare: aString
	       options: NSCaseInsensitiveSearch
		 range: ((NSRange){0, [self length]})];
}

/**
 * <p>Compares this instance with string. If locale is an NSLocale
 * instance and ICU is available, performs a comparison using the 
 * ICU collator for that locale. If locale is an instance of a class 
 * other than NSLocale, perform a comparison using +[NSLocale currentLocale].
 * If locale is nil, or ICU is not available, use a POSIX-style
 * collation (for example, latin capital letters A-Z are ordered before
 * all of the lowercase letter, a-z.) 
 * </p>
 * <p>mask may be <code>NSLiteralSearch</code>, which requests a literal
 * byte-by-byte
 * comparison, which is fastest but may return inaccurate results in cases
 * where two different composed character sequences may be used to express
 * the same character; <code>NSCaseInsensitiveSearch</code>, which ignores case
 * differences; <code>NSDiacriticInsensitiveSearch</code>
 * which ignores accent differences;
 * <code>NSNumericSearch</code>, which sorts groups of digits as numbers,
 * so "abc2" sorts before "abc100".
 * </p>
 * <p>compareRange refers to this instance, and should be set to 0..length
 * to compare the whole string.
 * </p>
 * <p>Returns <code>NSOrderedAscending</code>, <code>NSOrderedDescending</code>,
 * or <code>NSOrderedSame</code>, depending on whether this instance occurs
 * before or after string in lexical order, or is equal to it.
 * </p>
 */
- (NSComparisonResult) compare: (NSString *)string
		       options: (NSUInteger)mask
			 range: (NSRange)compareRange
			locale: (id)locale
{
  GS_RANGE_CHECK(compareRange, [self length]);
  if (nil == string)
    {
      [NSException raise: NSInvalidArgumentException
		  format: @"compare with nil"];
    }

#if GS_USE_ICU == 1
    {
      UCollator *coll = GSICUCollatorOpen(mask, locale);

      if (coll != NULL)
	{
	  NSUInteger countSelf = compareRange.length;
	  NSUInteger countOther = [string length];       
	  unichar *charsSelf;
	  unichar *charsOther;
	  UCollationResult result;
	  
	  charsSelf = NSZoneMalloc(NSDefaultMallocZone(),
	    countSelf * sizeof(unichar));
	  charsOther = NSZoneMalloc(NSDefaultMallocZone(),
	    countOther * sizeof(unichar));
	  // Copy to buffer

	  [self getCharacters: charsSelf range: compareRange];
	  [string getCharacters: charsOther range: NSMakeRange(0, countOther)];
	  
	  result = ucol_strcoll(coll,
	    charsSelf, countSelf, charsOther, countOther);

	  NSZoneFree(NSDefaultMallocZone(), charsSelf);
	  NSZoneFree(NSDefaultMallocZone(), charsOther);	  
	  ucol_close(coll); 
	  
	  switch (result)
	    {
	      case UCOL_EQUAL: return NSOrderedSame;
	      case UCOL_GREATER: return NSOrderedDescending;
	      case UCOL_LESS: return NSOrderedAscending;
	    }
	}
    }
#endif

  return strCompNsNs(self, string, mask, compareRange);
}

/**
 * Compares this instance with string, using +[NSLocale currentLocale].
 */
- (NSComparisonResult) localizedCompare: (NSString *)string
{
  return [self compare: string
               options: 0
                 range: NSMakeRange(0, [self length])
                locale: [NSLocale currentLocale]];
}

/**
 * Compares this instance with string, using +[NSLocale currentLocale],
 * ignoring case.
 */
- (NSComparisonResult) localizedCaseInsensitiveCompare: (NSString *)string
{
  return [self compare: string
               options: NSCaseInsensitiveSearch
                 range: NSMakeRange(0, [self length])
                locale: [NSLocale currentLocale]];
}

/**
 * Writes contents out to file at filename, using the default C string encoding
 * unless this would result in information loss, otherwise straight unicode.
 * The '<code>atomically</code>' option if set will cause the contents to be
 * written to a temp file, which is then closed and renamed to filename.  Thus,
 * an incomplete file at filename should never result.
 */
- (BOOL) writeToFile: (NSString*)filename
	  atomically: (BOOL)useAuxiliaryFile
{
  id	d = [self dataUsingEncoding: _DefaultStringEncoding];

  if (d == nil)
    {
      d = [self dataUsingEncoding: NSUnicodeStringEncoding];
    }
  return [d writeToFile: filename atomically: useAuxiliaryFile];
}

/**
 * Writes contents out to file at filename, using the default C string encoding
 * unless this would result in information loss, otherwise straight unicode.
 * The '<code>atomically</code>' option if set will cause the contents to be
 * written to a temp file, which is then closed and renamed to filename.  Thus,
 * an incomplete file at filename should never result.<br />
 * If there is a problem and error is not NULL, the cause of the problem is
 * returned in *error.
 */
- (BOOL) writeToFile: (NSString*)path
	  atomically: (BOOL)atomically
	    encoding: (NSStringEncoding)enc
	       error: (NSError**)error
{
  id	d = [self dataUsingEncoding: enc];

  if (d == nil)
    {
      if (error != 0)
        {
          *error = [NSError errorWithDomain: NSCocoaErrorDomain
	    code: NSFileWriteInapplicableStringEncodingError
	    userInfo: nil];
        }
      return NO;
    }
  return [d writeToFile: path
	        options: atomically ? NSDataWritingAtomic : 0
		  error: error];
}

/**
 * Writes contents out to url, using the default C string encoding
 * unless this would result in information loss, otherwise straight unicode.
 * See [NSURLHandle-writeData:] on which URL types are supported.
 * The '<code>atomically</code>' option is only heeded if the URL is a
 * <code>file://</code> URL; see -writeToFile:atomically: .<br />
 * If there is a problem and error is not NULL, the cause of the problem is
 * returned in *error.
 */
- (BOOL) writeToURL: (NSURL*)url
	 atomically: (BOOL)atomically
	    encoding: (NSStringEncoding)enc
	       error: (NSError**)error
{
  id	d = [self dataUsingEncoding: enc];

  if (d == nil)
    {
      d = [self dataUsingEncoding: NSUnicodeStringEncoding];
    }
  if (d == nil)
    {
      if (error != 0)
        {
          *error = [NSError errorWithDomain: NSCocoaErrorDomain
	    code: NSFileWriteInapplicableStringEncodingError
	    userInfo: nil];
        }
      return NO;
    }
  return [d writeToURL: url
	       options: atomically ? NSDataWritingAtomic : 0
		 error: error];
}

/**
 * Writes contents out to url, using the default C string encoding
 * unless this would result in information loss, otherwise straight unicode.
 * See [NSURLHandle-writeData:] on which URL types are supported.
 * The '<code>atomically</code>' option is only heeded if the URL is a
 * <code>file://</code> URL; see -writeToFile:atomically: .
 */
- (BOOL) writeToURL: (NSURL*)url atomically: (BOOL)atomically
{
  id	d = [self dataUsingEncoding: _DefaultStringEncoding];

  if (d == nil)
    {
      d = [self dataUsingEncoding: NSUnicodeStringEncoding];
    }
  return [d writeToURL: url atomically: atomically];
}

/* NSCopying Protocol */

- (id) copyWithZone: (NSZone*)zone
{
  /*
   * Default implementation should not simply retain ... the string may
   * have been initialised with freeWhenDone==NO and not own its
   * characters ... so the code which created it may destroy the memory
   * when it has finished with the original string ... leaving the
   * copy with pointers to invalid data.  So, we always copy in full.
   */
  return [[NSStringClass allocWithZone: zone] initWithString: self];
}

- (id) mutableCopyWithZone: (NSZone*)zone
{
  return [[GSMutableStringClass allocWithZone: zone] initWithString: self];
}

/* NSCoding Protocol */

- (void) encodeWithCoder: (NSCoder*)aCoder
{
  if ([aCoder allowsKeyedCoding])
    {
      [(NSKeyedArchiver*)aCoder _encodePropertyList: self forKey: @"NS.string"];
    }
  else
    {
      unsigned	count = [self length];

      [aCoder encodeValueOfObjCType: @encode(unsigned) at: &count];
      if (count > 0)
	{
	  NSStringEncoding	enc = NSUnicodeStringEncoding;
	  unichar		*chars;

	  /* For backwards-compatibility, we always encode/decode
	     'NSStringEncoding' (which really is an 'unsigned int') as
	     an 'int'.  Due to a bug, GCC up to 4.5 always encode all
	     enums as 'i' (int) regardless of the actual integer type
	     required to store them; we need to be able to read/write
	     archives compatible with GCC <= 4.5 so we explictly use
	     'int' to read/write these variables.  */
	  [aCoder encodeValueOfObjCType: @encode(int) at: &enc];

	  chars = NSZoneMalloc(NSDefaultMallocZone(), count*sizeof(unichar));
	  [self getCharacters: chars range: ((NSRange){0, count})];
	  [aCoder encodeArrayOfObjCType: @encode(unichar)
				  count: count
				     at: chars];
	  NSZoneFree(NSDefaultMallocZone(), chars);
	}
    }
}

- (id) initWithCoder: (NSCoder*)aCoder
{
  if ([aCoder allowsKeyedCoding])
    {
      if ([aCoder containsValueForKey: @"NS.string"])
        {
          NSString *string = nil;
      
          string = (NSString*)[(NSKeyedUnarchiver*)aCoder
                                  _decodePropertyListForKey: @"NS.string"];
          self = [self initWithString: string];
        }
      else if ([aCoder containsValueForKey: @"NS.bytes"])
        {
          id bytes = [(NSKeyedUnarchiver*)aCoder
                         decodeObjectForKey: @"NS.bytes"];

          if ([bytes isKindOfClass: NSStringClass])
            {
              self = [self initWithString: (NSString*)bytes];
            }
          else
            {
              self = [self initWithData: (NSData*)bytes 
                               encoding: NSUTF8StringEncoding];
            }
        }
      else
        {
          // empty string
          self = [self initWithString: @""];
        }
    }
  else
    {
      unsigned	count;
	
      [aCoder decodeValueOfObjCType: @encode(unsigned) at: &count];

      if (count > 0)
        {
	  NSStringEncoding	enc;
	  NSZone		*zone;
	
	  [aCoder decodeValueOfObjCType: @encode(int) at: &enc];
	  zone = [self zone];
	
	  if (enc == NSUnicodeStringEncoding)
	    {
	      unichar	*chars;
	
	      chars = NSZoneMalloc(zone, count*sizeof(unichar));
	      [aCoder decodeArrayOfObjCType: @encode(unichar)
		                      count: count
		                         at: chars];
	      self = [self initWithCharactersNoCopy: chars
					     length: count
				       freeWhenDone: YES];
	    }
	  else
	    {
	      unsigned char	*chars;
	
	      chars = NSZoneMalloc(zone, count+1);
	      [aCoder decodeArrayOfObjCType: @encode(unsigned char)
		                      count: count
				         at: chars];
	      self = [self initWithBytesNoCopy: chars
					length: count
				      encoding: enc
				  freeWhenDone: YES];
	    }
	}
      else
        {
	  self = [self initWithBytesNoCopy: (char *)""
				    length: 0
			          encoding: NSASCIIStringEncoding
			      freeWhenDone: NO];
	}
    }
  return self;
}

- (Class) classForCoder
{
  return NSStringClass;
}

- (id) replacementObjectForPortCoder: (NSPortCoder*)aCoder
{
  if ([aCoder isByref] == NO)
    return self;
  return [super replacementObjectForPortCoder: aCoder];
}

/**
 * <p>Attempts to interpret the receiver as a <em>property list</em>
 * and returns the result.  If the receiver does not contain a
 * string representation of a <em>property list</em> then the method
 * returns nil.
 * </p>
 * <p>Containers (arrays and dictionaries) are decoded as <em>mutable</em>
 * objects.
 * </p>
 * <p>There are three readable <em>property list</em> storage formats -
 * The binary format used by [NSSerializer] does not concern us here,
 * but there are two 'human readable' formats, the <em>traditional</em>
 * OpenStep format (which is extended in GNUstep) and the <em>XML</em> format.
 * </p>
 * <p>The [NSArray-descriptionWithLocale:indent:] and
 * [NSDictionary-descriptionWithLocale:indent:] methods
 * both generate strings containing traditional style <em>property lists</em>,
 * but [NSArray-writeToFile:atomically:] and
 * [NSDictionary-writeToFile:atomically:] generate either traditional or
 * XML style <em>property lists</em> depending on the value of the
 * GSMacOSXCompatible and NSWriteOldStylePropertyLists user defaults.<br />
 * If GSMacOSXCompatible is YES then XML <em>property lists</em> are
 * written unless NSWriteOldStylePropertyLists is also YES.<br />
 * By default GNUstep writes old style data and always supports reading of
 * either style.
 * </p>
 * <p>The traditional format is more compact and more easily readable by
 * people, but (without the GNUstep extensions) cannot represent date and
 * number objects (except as strings).  The XML format is more verbose and
 * less readable, but can be fed into modern XML tools and thus used to
 * pass data to non-OpenStep applications more readily.
 * </p>
 * <p>The traditional format is strictly ascii encoded, with any unicode
 * characters represented by escape sequences.  The XML format is encoded
 * as UTF8 data.
 * </p>
 * <p>Both the traditional format and the XML format permit comments to be
 * placed in <em>property list</em> documents.  In traditional format the
 * comment notations used in Objective-C programming are supported, while
 * in XML format, the standard SGML comment sequences are used.
 * </p>
 * <p>See the documentation for [NSPropertyListSerialization] for more
 * information on what a property list is.
 * </p>
 * <p>If the string cannot be parsed as a normal property list format,
 * this method also tries to parse it as 'strings file' format (see the
 * -propertyListFromStringsFileFormat method).
 * </p>
 */
- (id) propertyList
{
  NSData		*data;
  id			result = nil;
  NSPropertyListFormat	format;
  NSString		*error = nil;

  if ([self length] == 0)
    {
      return nil;
    }
  data = [self dataUsingEncoding: NSUTF8StringEncoding];
  NSAssert(data, @"Couldn't get utf8 data from string.");

  result = [NSPropertyListSerialization
    propertyListFromData: data
    mutabilityOption: NSPropertyListMutableContainers
    format: &format
    errorDescription: &error];

  if (result == nil)
    {
      extern id	GSPropertyListFromStringsFormat(NSString *string);

      NS_DURING
        {
          result = GSPropertyListFromStringsFormat(self);
        }
      NS_HANDLER
        {
          error = [NSString stringWithFormat:
            @"as property list {%@}, and as strings file {%@}",
            error, [localException reason]];
          result = nil;
        }
      NS_ENDHANDLER
      if (result == nil)
        {
          [NSException raise: NSGenericException
                      format: @"Parse failed - %@", error];
        }
    }
  return result;
}

/**
 * <p>Reads a <em>property list</em> (see -propertyList) from a simplified
 * file format.  This format is a traditional style property list file
 * containing a single dictionary, but with the leading '{' and trailing
 * '}' characters omitted.
 * </p>
 * <p>That is to say, the file contains only semicolon separated key/value
 * pairs (and optionally comments).  As a convenience, it is possible to
 * omit the equals sign and the value, so an entry consists of a key string
 * followed by a semicolon.  In this case, the value for that key is
 * assumed to be an empty string.
 * </p>
 * <example>
 *   // Strings file entries follow -
 *   key1 = " a string value";
 *   key2;	// This key has an empty string as a value.
 *   "Another key" = "a longer string value for th third key";
 * </example>
 */
- (NSDictionary*) propertyListFromStringsFileFormat
{
  extern id	GSPropertyListFromStringsFormat(NSString *string);

  return GSPropertyListFromStringsFormat(self);
}

/**
  * Returns YES if the receiver contains string, otherwise, NO.
  */
- (BOOL) containsString: (NSString *)string
{
  return [self rangeOfString: string].location != NSNotFound;
}

@end

/**
 * This is the mutable form of the [NSString] class.
 */
@implementation NSMutableString

+ (id) allocWithZone: (NSZone*)z
{
  if (self == NSMutableStringClass)
    {
      return NSAllocateObject(GSMutableStringClass, 0, z);
    }
  else
    {
      return NSAllocateObject(self, 0, z);
    }
}

// Creating Temporary Strings

/**
 * Constructs an empty string.
 */
+ (id) string
{
  return AUTORELEASE([[GSMutableStringClass allocWithZone:
    NSDefaultMallocZone()] initWithCapacity: 0]);
}

/**
 * Constructs an empty string with initial buffer size of capacity.
 */
+ (NSMutableString*) stringWithCapacity: (NSUInteger)capacity
{
  return AUTORELEASE([[GSMutableStringClass allocWithZone:
    NSDefaultMallocZone()] initWithCapacity: capacity]);
}

/**
 * Create a string of unicode characters.
 */
// Inefficient implementation.
+ (id) stringWithCharacters: (const unichar*)characters
		     length: (NSUInteger)length
{
  return AUTORELEASE([[GSMutableStringClass allocWithZone:
    NSDefaultMallocZone()] initWithCharacters: characters length: length]);
}

/**
 * Load contents of file at path into a new string.  Will interpret file as
 * containing direct unicode if it begins with the unicode byte order mark,
 * else converts to unicode using default C string encoding.
 */
+ (id) stringWithContentsOfFile: (NSString *)path
{
  return AUTORELEASE([[GSMutableStringClass allocWithZone:
    NSDefaultMallocZone()] initWithContentsOfFile: path]);
}

/**
 * Create a string based on the given C (char[]) string, which should be
 * null-terminated and encoded in the default C string encoding.  (Characters
 * will be converted to unicode representation internally.)
 */
+ (id) stringWithCString: (const char*)byteString
{
  return AUTORELEASE([[GSMutableStringClass allocWithZone:
    NSDefaultMallocZone()] initWithCString: byteString]);
}

/**
 * Create a string based on the given C (char[]) string, which may contain
 * null bytes and should be encoded in the default C string encoding.
 * (Characters will be converted to unicode representation internally.)
 */
+ (id) stringWithCString: (const char*)byteString
		  length: (NSUInteger)length
{
  return AUTORELEASE([[GSMutableStringClass allocWithZone:
    NSDefaultMallocZone()] initWithCString: byteString length: length]);
}

/**
 * Creates a new string using C printf-style formatting.  First argument should
 * be a constant format string, like '<code>@"float val = %f"</code>', remaining
 * arguments should be the variables to print the values of, comma-separated.
 */
+ (id) stringWithFormat: (NSString*)format, ...
{
  va_list ap;
  va_start(ap, format);
  self = [super stringWithFormat: format arguments: ap];
  va_end(ap);
  return self;
}

/** <init/> <override-subclass />
 * Constructs an empty string with initial buffer size of capacity.<br />
 * Calls -init (which does nothing but maintain MacOS-X compatibility),
 * and needs to be re-implemented in subclasses in order to have all
 * other initialisers work.
 */
- (id) initWithCapacity: (NSUInteger)capacity
{
  self = [self init];
  return self;
}

- (id) initWithCharactersNoCopy: (unichar*)chars
			 length: (NSUInteger)length
		   freeWhenDone: (BOOL)flag
{
  if ((self = [self initWithCapacity: length]) != nil && length > 0)
    {
      NSString	*tmp;

      tmp = [NSString allocWithZone: NSDefaultMallocZone()];
      tmp = [tmp initWithCharactersNoCopy: chars
				   length: length
			     freeWhenDone: flag];
      [self replaceCharactersInRange: NSMakeRange(0,0) withString: tmp];
      RELEASE(tmp);
    }
  return self;
}

- (id) initWithCStringNoCopy: (char*)chars
		      length: (NSUInteger)length
		freeWhenDone: (BOOL)flag
{
  if ((self = [self initWithCapacity: length]) != nil && length > 0)
    {
      NSString	*tmp;

      tmp = [NSString allocWithZone: NSDefaultMallocZone()];
      tmp = [tmp initWithCStringNoCopy: chars
				length: length
			  freeWhenDone: flag];
      [self replaceCharactersInRange: NSMakeRange(0,0) withString: tmp];
      RELEASE(tmp);
    }
  return self;
}

// Modify A String

/**
 *  Modifies this string by appending aString.
 */
- (void) appendString: (NSString*)aString
{
  NSRange aRange;

  aRange.location = [self length];
  aRange.length = 0;
  [self replaceCharactersInRange: aRange withString: aString];
}

/**
 *  Modifies this string by appending string described by given format.
 */
// Inefficient implementation.
- (void) appendFormat: (NSString*)format, ...
{
  va_list	ap;
  id		tmp;

  va_start(ap, format);
  tmp = [[NSStringClass allocWithZone: NSDefaultMallocZone()]
    initWithFormat: format arguments: ap];
  va_end(ap);
  [self appendString: tmp];
  RELEASE(tmp);
}

- (Class) classForCoder
{
  return NSMutableStringClass;
}

/**
 * Modifies this instance by deleting specified range of characters.
 */
- (void) deleteCharactersInRange: (NSRange)range
{
  [self replaceCharactersInRange: range withString: nil];
}

/**
 * Modifies this instance by inserting aString at loc.
 */
- (void) insertString: (NSString*)aString atIndex: (NSUInteger)loc
{
  NSRange range = {loc, 0};
  [self replaceCharactersInRange: range withString: aString];
}

/**
 * Modifies this instance by deleting characters in range and then inserting
 * aString at its beginning.
 */
- (void) replaceCharactersInRange: (NSRange)range
		       withString: (NSString*)aString
{
  [self subclassResponsibility: _cmd];
}

/**
 * Replaces all occurrences of the replace string with the by string,
 * for those cases where the entire replace string lies within the
 * specified searchRange value.<br />
 * The value of opts determines the direction of the search is and
 * whether only leading/trailing occurrences (anchored search) of
 * replace are substituted.<br />
 * Raises NSInvalidArgumentException if either string argument is nil.<br />
 * Raises NSRangeException if part of searchRange is beyond the end
 * of the receiver.
 */
- (NSUInteger) replaceOccurrencesOfString: (NSString*)replace
                               withString: (NSString*)by
                                  options: (NSUInteger)opts
                                    range: (NSRange)searchRange
{
  NSRange	range;
  unsigned int	count = 0;
  GSRSFunc	func;

  if ([replace isKindOfClass: NSStringClass] == NO)
    {
      [NSException raise: NSInvalidArgumentException
		  format: @"%@ bad search string", NSStringFromSelector(_cmd)];
    }
  if ([by isKindOfClass: NSStringClass] == NO)
    {
      [NSException raise: NSInvalidArgumentException
		  format: @"%@ bad replace string", NSStringFromSelector(_cmd)];
    }
  if (NSMaxRange(searchRange) > [self length])
    {
      [NSException raise: NSInvalidArgumentException
		  format: @"%@ bad search range", NSStringFromSelector(_cmd)];
    }
  func = GSPrivateRangeOfString(self, replace);
  range = (*func)(self, replace, opts, searchRange);

  if (range.length > 0)
    {
      unsigned	byLen = [by length];
      SEL	sel;
      void	(*imp)(id, SEL, NSRange, NSString*);

      sel = @selector(replaceCharactersInRange:withString:);
      imp = (void(*)(id, SEL, NSRange, NSString*))[self methodForSelector: sel];
      do
	{
	  count++;
	  (*imp)(self, sel, range, by);
	  if ((opts & NSBackwardsSearch) == NSBackwardsSearch)
	    {
	      searchRange.length = range.location - searchRange.location;
	    }
	  else
	    {
	      unsigned int	newEnd;

	      newEnd = NSMaxRange(searchRange) + byLen - range.length;
	      searchRange.location = range.location + byLen;
	      searchRange.length = newEnd - searchRange.location;
	    }
	  /* We replaced something and now need to scan again.
	   * As we modified the receiver, we must refresh the
	   * method implementation for searching.
	   */
	  func = GSPrivateRangeOfString(self, replace);
	  range = (*func)(self, replace, opts, searchRange);
	}
      while (range.length > 0);
    }
  return count;
}

/**
 * Modifies this instance by replacing contents with those of aString.
 */
- (void) setString: (NSString*)aString
{
  NSRange range = {0, [self length]};
  [self replaceCharactersInRange: range withString: aString];
}

@end