File: CFString.c

package info (click to toggle)
gnustep-corebase 0.1.1%2B20230710-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,608 kB
  • sloc: ansic: 25,359; objc: 4,347; cpp: 75; xml: 49; makefile: 24; sh: 7
file content (1802 lines) | stat: -rw-r--r-- 51,997 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
/* CFString.c
   
   Copyright (C) 2011 Free Software Foundation, Inc.
   
   Written by: Stefan Bidigaray
   Date: May, 2011
   
   This file is part of GNUstep CoreBase Library.
   
   This library is free software; you can redisibute 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.1 of the License, or (at your option) any later version.

   This library is disibuted 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; see the file COPYING.LIB.
   If not, see <http://www.gnu.org/licenses/> or write to the 
   Free Software Foundation, 51 Franklin Street, Fifth Floor, 
   Boston, MA 02110-1301, USA.
*/

#include "CoreFoundation/CFRuntime.h"
#include "CoreFoundation/CFBase.h"
#include "CoreFoundation/CFArray.h"
#include "CoreFoundation/CFData.h"
#include "CoreFoundation/CFDictionary.h"
#include "CoreFoundation/CFNumberFormatter.h"
#include "CoreFoundation/CFString.h"
#include "CoreFoundation/CFStringEncodingExt.h"
#include "CoreFoundation/GSCharacter.h"
#include "CoreFoundation/GSUnicode.h"

#include "GSPrivate.h"
#include "GSObjCRuntime.h"
#include "GSMemory.h"

#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>

#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_UTRANS_H)
#include <unicode/utrans.h>
#endif
#if defined(HAVE_ICU_H)
#include <icu.h>
#endif

#define BUFFER_SIZE 512

CONST_STRING_DECL (kCFStringTransformStripCombiningMarks,
                   "NFD; [:nonspacing mark:]Remove; NFC");
CONST_STRING_DECL (kCFStringTransformToLatin, "Any-Latin");
CONST_STRING_DECL (kCFStringTransformFullwidthHalfwidth,
                   "Fullwidth-Halfwidth");
CONST_STRING_DECL (kCFStringTransformLatinKatakana, "Latin-Katakana");
CONST_STRING_DECL (kCFStringTransformLatinHiragana, "Latin-Hiragana");
CONST_STRING_DECL (kCFStringTransformHiraganaKatakana, "Hiragana-Katakana");
CONST_STRING_DECL (kCFStringTransformMandarinLatin, "Mandarin-Latin");
CONST_STRING_DECL (kCFStringTransformLatinHangul, "Latin-Hangul");
CONST_STRING_DECL (kCFStringTransformLatinArabic, "Latin-Arabic");
CONST_STRING_DECL (kCFStringTransformLatinHebrew, "Latin-Hebrew");
CONST_STRING_DECL (kCFStringTransformLatinThai, "Latin-Thai");
CONST_STRING_DECL (kCFStringTransformLatinCyrillic, "Latin-Cyrillic");
CONST_STRING_DECL (kCFStringTransformLatinGreek, "Latin-Greek");
CONST_STRING_DECL (kCFStringTransformToXMLHex, "Any-Hex/XML");
CONST_STRING_DECL (kCFStringTransformToUnicodeName, "Any-Name");
CONST_STRING_DECL (kCFStringTransformStripDiacritics,
                   "NFD; [:nonspacing marks:]Remove; NFC");

/* CFString has two possible internal encodings:
     * UTF-16 (preferable)
     * ASCII
   If the encoding is not one of the two listed above, it will be converted
   to UTF-16 any character is not ASCII.
*/

struct __CFString
{
  CFRuntimeBase _parent;
  void *_contents;
  CFIndex _count;
  CFHashCode _hash;
  CFAllocatorRef _deallocator;
};

struct __CFMutableString
{
  CFRuntimeBase _parent;
  UniChar *_contents;
  CFIndex _count;
  CFHashCode _hash;
  CFAllocatorRef _allocator;
  CFIndex _capacity;
};

static CFTypeID _kCFStringTypeID;

/* These are some masks to access the data in CFRuntimeBase's _flags.info
   field. */
enum
{
  _kCFStringIsMutable = (1 << 0),
  _kCFStringIsInline = (1 << 1),
  _kCFStringIsUnicode = (1 << 2),
  _kCFStringHasLengthByte = (1 << 3),   /* This is used for Pascal strings */
  _kCFStringHasNullByte = (1 << 4)
};

// TODO: dispatch to ObjC in all of these methods OR check its use

CF_INLINE Boolean
CFStringIsMutable (CFStringRef str)
{
  return
    ((CFRuntimeBase *) str)->_flags.info & _kCFStringIsMutable ? true : false;
}

CF_INLINE Boolean
CFStringIsUnicode (CFStringRef str)
{
  return ((CFRuntimeBase *) str)->
    _flags.info & _kCFStringIsUnicode ? true : false;
}

CF_INLINE Boolean
CFStringIsInline (CFStringRef str)
{
  return
    ((CFRuntimeBase *) str)->_flags.info & _kCFStringIsInline ? true : false;
}

CF_INLINE Boolean
CFStringHasNullByte (CFStringRef str)
{
  return
    ((CFRuntimeBase *) str)->
    _flags.info & _kCFStringHasNullByte ? true : false;
}

CF_INLINE void
CFStringSetMutable (CFStringRef str)
{
  ((CFRuntimeBase *) str)->_flags.info |= _kCFStringIsMutable;
}

CF_INLINE void
CFStringSetUnicode (CFStringRef str)
{
  ((CFRuntimeBase *) str)->_flags.info |= _kCFStringIsUnicode;
}

CF_INLINE void
CFStringSetInline (CFStringRef str)
{
  ((CFRuntimeBase *) str)->_flags.info |= _kCFStringIsInline;
}

CF_INLINE void
CFStringSetNullByte (CFStringRef str)
{
  ((CFRuntimeBase *) str)->_flags.info |= _kCFStringHasNullByte;
}



static void
CFStringFinalize (CFTypeRef cf)
{
  CFStringRef str = (CFStringRef) cf;

  if (!CFStringIsInline (str))
    CFAllocatorDeallocate (str->_deallocator, str->_contents);
}

static Boolean
CFStringEqual (CFTypeRef cf1, CFTypeRef cf2)
{
  return CFStringCompare (cf1, cf2, 0) == 0 ? true : false;
}

static CFHashCode
CFStringHash (CFTypeRef cf)
{
  CFStringRef str = (CFStringRef) cf;
  UniChar *buf;
  CFIndex len;
  Boolean isObjc;
  CFHashCode hash;

  isObjc = CF_IS_OBJC (_kCFStringTypeID, str);

  if (!isObjc)
    {
      if (str->_hash == 0)
        {
          if (CFStringIsUnicode (str))
            {
              len = CFStringGetLength (str) * sizeof (UniChar);
              ((struct __CFString *) str)->_hash =
                GSHashBytes (str->_contents, len);
              return str->_hash;
            }
        }
      else
        return str->_hash;
    }

  len = CFStringGetLength (str) * sizeof (UniChar);

  buf = CFAllocatorAllocate (kCFAllocatorSystemDefault, len, 0);
  CFStringGetCharacters (str, CFRangeMake (0, len / 2), buf);

  hash = GSHashBytes (buf, len);
  if (!isObjc)
    ((struct __CFString *) str)->_hash = hash;

  CFAllocatorDeallocate (kCFAllocatorSystemDefault, buf);
  return hash;
}

static CFStringRef
CFStringCopyFormattingDesc (CFTypeRef cf, CFDictionaryRef formatOptions)
{
  return CFStringCreateCopy (kCFAllocatorSystemDefault, cf);
}

static const CFRuntimeClass CFStringClass = {
  0,
  "CFString",
  NULL,
  (CFTypeRef (*)(CFAllocatorRef, CFTypeRef)) CFStringCreateCopy,
  CFStringFinalize,
  CFStringEqual,
  CFStringHash,
  CFStringCopyFormattingDesc,
  NULL
};

static GSMutex static_strings_lock;
static CFMutableDictionaryRef static_strings;
/*
 * Hack to allocated CFStrings uniquely without compiler support.
 */
CFStringRef
__CFStringMakeConstantString (const char *str)
{
  CFStringRef old;

  if (static_strings == NULL)
    {
      /* The 170 capacity is really arbitrary.  I just wanted to make the
       * number large enough so that the hash table size comes out to 257,
       * a table large enough to fit most needs before needing to expand.
       */
      GSMutexLock (&static_strings_lock);
      if (static_strings == NULL)
        static_strings = CFDictionaryCreateMutable (NULL, 170, NULL, NULL);
      GSMutexUnlock (&static_strings_lock);
    }

  old = (CFStringRef) CFDictionaryGetValue (static_strings, str);

  /* Return the existing string pointer if we have one. */
  if (NULL != old)
    return old;

  GSMutexLock (&static_strings_lock);
  /* Check again in case another thread added this string to the table while
   * we were waiting on the mutex. */
  old = (CFStringRef) CFDictionaryGetValue (static_strings, str);
  if (NULL == old)
    {
      struct __CFString *new_const_str;

      new_const_str =
        CFAllocatorAllocate (NULL, sizeof (struct __CFString), 0);
      assert (new_const_str);

      /* Using _CFRuntimeInitStaticInstance() guarantees that any CFRetain or
       * CFRelease calls on object will be a no-op.
       */
      _CFRuntimeInitStaticInstance (new_const_str, _kCFStringTypeID);
      new_const_str->_contents = (void *) str;
      new_const_str->_count = strlen (str);
      new_const_str->_hash = 0;
      new_const_str->_deallocator = NULL;

      CFDictionaryAddValue (static_strings, str,
                            (const void *) new_const_str);
      old = new_const_str;
    }
  GSMutexUnlock (&static_strings_lock);

  return old;
}

void
CFStringInitialize (void)
{
  _kCFStringTypeID = _CFRuntimeRegisterClass (&CFStringClass);
  GSMutexInitialize (&static_strings_lock);
}



void
CFShow (CFTypeRef obj)
{
  CFStringRef str;
  const char *out;
  char buffer[256];

  str = CFCopyDescription (obj);
  if (str)
    {
      out = CFStringGetCStringPtr (str, kCFStringEncodingASCII);
      if (out == NULL)
        {
          if (CFStringGetCString (str, buffer, 256, kCFStringEncodingASCII))
            out = buffer;
        }
      CFRelease (str);
    }
  else
    {
      out = NULL;
    }
  fprintf (stderr, "%s\n", out);
}

void
CFShowStr (CFStringRef s)
{
  fprintf (stderr, "Length %ld\n", (long) CFStringGetLength (s));
  fprintf (stderr, "IsWide %d\n", CFStringIsUnicode (s));
  fprintf (stderr, "InlineContents %d\n", CFStringIsInline (s));
  fprintf (stderr, "Allocator %p\n", CFGetAllocator (s));
  fprintf (stderr, "Mutable %d\n", CFStringIsMutable (s));
  fprintf (stderr, "Contents ");
  CFShow (s);
}

CFTypeID
CFStringGetTypeID (void)
{
  return _kCFStringTypeID;
}

/* CFStringCreateImmutable function will return an inlined string whenever
   possible.  The contents may or may not be inlined if a NoCopy function
   is called. With this in mind, CFStringCreateWithBytes will return a
   string with the content inlined and CFStringCreateWithBytesNoCopy will not
   have inlined content if, and only if, the input bytes are in one of the
   internal encodings (ASCII or UTF-16).
 */
#define CFSTRING_SIZE \
  sizeof(struct __CFString) - sizeof(struct __CFRuntimeBase)

static CFStringRef
CFStringCreateImmutable (CFAllocatorRef alloc, const UInt8 * bytes,
                         CFIndex numBytes, CFStringEncoding encoding,
                         Boolean isExtRep, CFAllocatorRef contentsDealloc,
                         Boolean copy)
{
  struct __CFString *new;
  UniChar b[BUFFER_SIZE];
  UniChar *buffer;
  UniChar *bufferStart;
  CFIndex need;
  CFIndex extra;

  buffer = b;
  bufferStart = b;

  /* Check if we can store this string as ASCII */
  if (__CFStringEncodingIsSupersetOfASCII (encoding))
    {
      const UInt8 *s;
      const UInt8 *limit;

      s = bytes;
      limit = s + numBytes;
      while (s < limit)
        {
          if (*s++ > 0x7F)
            break;
        }
      if (s >= limit)
        encoding = kCFStringEncodingASCII;
    }

  if (encoding == kCFStringEncodingASCII)
    {
      need = numBytes;
      extra = numBytes + 1;
    }
  else
    {
      const UInt8 *src;

      src = bytes;
      /* We'll include a loss character for this conversion in case
         there is an error in the input stream. We dont' want to fail
         just because someone included an invalid code point/unit.
         The loss character will be the Unicode replacement character U+FFFD.
       */
      need = GSUnicodeFromEncoding (&buffer, buffer + BUFFER_SIZE, encoding,
                                    &src, src + numBytes, 0xFFFD);
      if (need < 0)             /* There is something seriously wrong! */
        return NULL;
      extra = (need + 1) * sizeof (UniChar);
    }
  if (!copy)
    {
      if (encoding == kCFStringEncodingUTF16)
        {
          UniChar c;

          c = *((const UniChar *) bytes);
          if (c == kGSUTF16CharacterSwappedByteOrderMark)
            copy = true;
        }
      else if (encoding != kCFStringEncodingASCII)
        {
          copy = true;
        }
#if __BIG_ENDIAN__
      else if (encoding == kCFStringEncodingUTF16LE)
        {
          copy = true;
        }
#else
      else if (encoding == kCFStringEncodingUTF16BE)
        {
          copy = true;
        }
#endif
    }

  new = (struct __CFString *) _CFRuntimeCreateInstance (alloc,
                                                        _kCFStringTypeID,
                                                        CFSTRING_SIZE +
                                                        extra, NULL);
  if (new)
    {
      if (contentsDealloc == NULL)
        contentsDealloc = CFAllocatorGetDefault ();
      new->_deallocator = CFRetain (contentsDealloc);

      if (copy)
        {
          new->_contents = &(new[1]);

          if (encoding == kCFStringEncodingASCII)
            {
              GSMemoryCopy (new->_contents, bytes, numBytes);
            }
          else if (extra <= BUFFER_SIZE)
            {
              GSMemoryCopy (new->_contents, bufferStart,
                            need * sizeof (UniChar));
              CFStringSetUnicode (new);
            }
          else
            {
              UniChar *contents;

              contents = new->_contents;
              GSUnicodeFromEncoding (&contents, contents + need, encoding,
                                     &bytes, bytes + numBytes, 0xFFFD);
              CFStringSetUnicode (new);
            }

          new->_count = need;
          CFStringSetInline (new);
          CFStringHasNullByte (new);
        }
      else
        {
          new->_contents = (void *) bytes;
          new->_count = encoding == kCFStringEncodingASCII
            ? numBytes : numBytes / sizeof (UniChar);
          if (encoding != kCFStringEncodingASCII)
            CFStringSetUnicode (new);
        }
    }

  return (CFStringRef) new;
}

CFStringRef
CFStringCreateWithBytes (CFAllocatorRef alloc, const UInt8 * bytes,
                         CFIndex numBytes, CFStringEncoding encoding,
                         Boolean isExternalRepresentation)
{
  return CFStringCreateImmutable (alloc, bytes, numBytes, encoding,
                                  isExternalRepresentation, NULL, true);
}

CFStringRef
CFStringCreateWithBytesNoCopy (CFAllocatorRef alloc, const UInt8 * bytes,
                               CFIndex numBytes, CFStringEncoding encoding,
                               Boolean isExternalRepresentation,
                               CFAllocatorRef contentsDeallocator)
{
  return CFStringCreateImmutable (alloc, bytes, numBytes, encoding,
                                  isExternalRepresentation,
                                  contentsDeallocator, false);
}

CFStringRef
CFStringCreateCopy (CFAllocatorRef alloc, CFStringRef str)
{
  if (CF_IS_OBJC (_kCFStringTypeID, str))
    {
      CFIndex length = CFStringGetLength (str);
      UniChar *buf =
        (UniChar *) CFAllocatorAllocate (alloc, sizeof (UniChar) * length, 0);

      CFStringGetCharacters (str, CFRangeMake (0, length), buf);
      return CFStringCreateWithCharactersNoCopy (alloc, buf, length, alloc);
    }

  CFIndex length;
  CFStringRef new;
  CFStringEncoding enc;

  if (alloc == NULL)
    alloc = CFAllocatorGetDefault ();

  if (CFGetAllocator (str) == alloc && !CFStringIsMutable (str))
    return CFRetain (str);

  length =
    CFStringIsUnicode (str) ? str->_count * sizeof (UniChar) : str->_count;
  enc =
    CFStringIsUnicode (str) ? kCFStringEncodingUTF16 : kCFStringEncodingASCII;
  new = CFStringCreateWithBytes (alloc, str->_contents, length, enc, false);

  return new;
}

CFStringRef
CFStringCreateWithFileSystemRepresentation (CFAllocatorRef alloc,
                                            const char *buffer)
{
  /* FIXME: Need to make sure the system encoding will work here. */
  return CFStringCreateWithCString (alloc, buffer,
                                    CFStringGetSystemEncoding ());
}

CFStringRef
CFStringCreateFromExternalRepresentation (CFAllocatorRef alloc,
                                          CFDataRef data,
                                          CFStringEncoding encoding)
{
  const UInt8 *bytes = CFDataGetBytePtr (data);
  CFIndex numBytes = CFDataGetLength (data);
  return CFStringCreateWithBytes (alloc, bytes, numBytes, encoding, true);
}

CFStringRef
CFStringCreateWithCharacters (CFAllocatorRef alloc, const UniChar * chars,
                              CFIndex numChars)
{
  return CFStringCreateWithBytes (alloc, (const UInt8 *) chars,
                                  numChars * sizeof (UniChar),
                                  kCFStringEncodingUnicode, false);
}

CFStringRef
CFStringCreateWithCharactersNoCopy (CFAllocatorRef alloc,
                                    const UniChar * chars, CFIndex numChars,
                                    CFAllocatorRef contentsDeallocator)
{
  return CFStringCreateWithBytesNoCopy (alloc, (const UInt8 *) chars,
                                        numChars * sizeof (UniChar),
                                        kCFStringEncodingUnicode, false,
                                        contentsDeallocator);
}

CFStringRef
CFStringCreateWithCString (CFAllocatorRef alloc, const char *cStr,
                           CFStringEncoding encoding)
{
  CFIndex len = strlen (cStr);
  return CFStringCreateWithBytes (alloc, (const UInt8 *) cStr, len, encoding,
                                  false);
}

CFStringRef
CFStringCreateWithCStringNoCopy (CFAllocatorRef alloc, const char *cStr,
                                 CFStringEncoding encoding,
                                 CFAllocatorRef contentsDeallocator)
{
  CFIndex len = strlen (cStr);
  return CFStringCreateWithBytesNoCopy (alloc, (const UInt8 *) cStr, len,
                                        encoding, false, contentsDeallocator);
}

CFStringRef
CFStringCreateWithFormat (CFAllocatorRef alloc, CFDictionaryRef formatOptions,
                          CFStringRef format, ...)
{
  CFStringRef result;
  va_list args;

  va_start (args, format);
  result =
    CFStringCreateWithFormatAndArguments (alloc, formatOptions, format, args);
  va_end (args);

  return result;
}

CFStringRef
CFStringCreateWithFormatAndArguments (CFAllocatorRef alloc,
                                      CFDictionaryRef formatOptions,
                                      CFStringRef format, va_list arguments)
{
  Boolean free_fmt_str = false;
  CFIndex str_len;
  CFIndex fmt_str_len;
  UniChar buf[BUFFER_SIZE];
  UniChar *str = buf;
  const UniChar *fmt_str;
  CFStringRef fmted_str;

  fmt_str_len = CFStringGetLength (format);
  fmt_str = CFStringGetCharactersPtr (format);
  if (fmt_str == 0)
    {
      CFRange range;

      free_fmt_str = true;
      fmt_str = CFAllocatorAllocate (kCFAllocatorSystemDefault,
                                     fmt_str_len * sizeof (UniChar), 0);
      range = CFRangeMake (0, fmt_str_len);
      CFStringGetCharacters (format, range, (UniChar *) fmt_str);
    }
  str_len = GSUnicodeFormatWithArguments (str, BUFFER_SIZE, formatOptions,
                                          fmt_str, fmt_str_len, arguments);
  if (str_len > BUFFER_SIZE)
    {
      /* The buffer was not long enough for the formatted string, so we will
       * need to allocate a longer buffer and try again.
       */
      str = CFAllocatorAllocate (kCFAllocatorSystemDefault,
                                 str_len * sizeof (UniChar), 0);
      str_len = GSUnicodeFormatWithArguments (str, str_len, formatOptions,
                                              fmt_str, fmt_str_len,
                                              arguments);

    }
  if (str_len < 0)
    return NULL;

  fmted_str = CFStringCreateWithCharacters (alloc, (const UniChar *) str,
                                            str_len);
  if (free_fmt_str)
    CFAllocatorDeallocate (kCFAllocatorSystemDefault, (void *) fmt_str);
  if (str != buf)
    CFAllocatorDeallocate (kCFAllocatorSystemDefault, str);

  return fmted_str;
}

CFStringRef
CFStringCreateWithSubstring (CFAllocatorRef alloc, CFStringRef str,
                             CFRange range)
{
  void *contents;
  CFIndex len;
  CFStringEncoding enc;

  if (CFStringIsUnicode (str))
    {
      enc = kCFStringEncodingUnicode;
      len = range.length * sizeof (UniChar);
      contents = ((UniChar *) str->_contents) + range.location;
    }
  else
    {
      enc = kCFStringEncodingASCII;
      len = range.length;
      contents = ((char *) str->_contents) + range.location;
    }

  return CFStringCreateWithBytes (alloc, (const UInt8 *) contents, len, enc,
                                  false);
}

CFDataRef
CFStringCreateExternalRepresentation (CFAllocatorRef alloc,
                                      CFStringRef str,
                                      CFStringEncoding encoding,
                                      UInt8 lossByte)
{
  UInt8 *buffer;
  CFRange range;
  CFIndex converted;
  CFIndex strLen;
  CFIndex len;
  CFIndex usedLen = 0;

  strLen = CFStringGetLength (str);
  range = CFRangeMake (0, strLen);
  converted = CFStringGetBytes (str, range, encoding, lossByte, true, NULL, 0, &len);
  if (converted == 0)
    return NULL;
  len += 1;             /* include space for a NULL byte. */

  buffer = CFAllocatorAllocate (alloc, len, 0);

  converted = CFStringGetBytes (str, range, encoding, lossByte,
                                true, buffer, len, &usedLen);

  if (converted == 0)
    {
      CFAllocatorDeallocate (alloc, buffer);
      return NULL;
    }

  return CFDataCreateWithBytesNoCopy (alloc, buffer, usedLen, alloc);
}

const UniChar *
CFStringGetCharactersPtr (CFStringRef str)
{
  if (!CF_IS_OBJC (_kCFStringTypeID, str) && CFStringIsUnicode (str))
    return str->_contents;

  return NULL;
}

const char *
CFStringGetCStringPtr (CFStringRef str, CFStringEncoding enc)
{
  CF_OBJC_FUNCDISPATCHV (_kCFStringTypeID, const char *, str,
                         "cStringUsingEncoding:",
                         CFStringConvertEncodingToNSStringEncoding (enc));

  return (!CFStringIsUnicode (str)
          && __CFStringEncodingIsSupersetOfASCII (enc)) ? str->
    _contents : NULL;
}

CFIndex
CFStringGetBytes (CFStringRef str, CFRange range, CFStringEncoding enc,
                  UInt8 lossByte, Boolean isExtRep, UInt8 * buffer,
                  CFIndex maxBufLen, CFIndex * usedBufLen)
{
  UInt8 *bufferStart;
  const UniChar *sUnicode;
  CFIndex converted = 0;

  if (CF_IS_OBJC (_kCFStringTypeID, str))
    {
      /* Boolean b; */
      uintptr_t opts = 0;

      if (lossByte != 0)
        opts |= 1;              /* NSStringEncodingConversionAllowLossy */
      if (isExtRep != 0)
        opts |= 2;              /*NSStringEncodingConversionExternalRepresentation */

      // FIXME: Base's NSString doesn't implement getBytes:... yet!
      *usedBufLen = 0;
      return 0;

      /*
         CF_OBJC_CALLV (Boolean, b, str,
         "getBytes:maxLength:usedLength:encoding:options:range:remainingRange:",
         buffer, maxBufLen, usedBufLen,
         CFStringConvertEncodingToNSStringEncoding (enc), opts,
         range, NULL);

         return b ? *usedBufLen : 0;
       */
    }

  bufferStart = buffer;
  sUnicode = CFStringGetCharactersPtr (str);

  if (sUnicode)
    {
      const UniChar *sUnicodeStart;
      const UniChar *sLimit;

      sUnicodeStart = sUnicode + range.location;
      sUnicode = sUnicodeStart;
      sLimit = sUnicodeStart + range.length;
      /* It is safe to discard the return value in this case. */
      GSUnicodeToEncoding (&buffer, buffer + maxBufLen, enc, &sUnicode,
                           sLimit, lossByte, isExtRep);
      converted = sUnicode - sUnicodeStart;
    }
  else if (__CFStringEncodingIsSupersetOfASCII (enc))
    {
      const char *sCString;

      sCString = CFStringGetCStringPtr (str, kCFStringEncodingASCII);
      if (sCString)
        {
          sCString += range.location;
          converted = range.length > maxBufLen ? maxBufLen : range.length;
          GSMemoryCopy (buffer, sCString, converted);
          buffer += converted;
        }
      else
        {
          converted = 0;
        }
    }
  else if (enc == kCFStringEncodingUnicode)
    {
      range.length =
        range.length >
        (maxBufLen / sizeof (UniChar)) ? maxBufLen /
        sizeof (UniChar) : range.length;
      CFStringGetCharacters (str, range, (UniChar *) buffer);
      buffer += range.length * sizeof (UniChar);
      converted = range.length;
    }
  if (usedBufLen)
    *usedBufLen = buffer - bufferStart;

  return converted;             /* FIXME */
}

void
CFStringGetCharacters (CFStringRef str, CFRange range, UniChar * buffer)
{
  CF_OBJC_FUNCDISPATCHV (_kCFStringTypeID, void, str,
                         "getCharacters:range:", buffer, range);

  if (CFStringIsUnicode (str))
    {
      memcpy (buffer, ((UniChar *) str->_contents) + range.location,
              range.length * sizeof (UniChar));
    }
  else
    {
      UInt8 *c;
      UInt8 *stop;

      c = str->_contents + range.location;
      stop = c + range.length;
      while (c < stop)
        *buffer++ = *c++;
    }
}

Boolean
CFStringGetCString (CFStringRef str, char *buffer, CFIndex bufferSize,
                    CFStringEncoding encoding)
{
  CFIndex len = CFStringGetLength (str);
  CFIndex used;

  CF_OBJC_FUNCDISPATCHV (_kCFStringTypeID, Boolean, str,
                         "getCString:maxLength:encoding:", buffer, bufferSize,
                         CFStringConvertEncodingToNSStringEncoding
                         (encoding));

  if (CFStringGetBytes (str, CFRangeMake (0, len), encoding, 0, false,
                        (UInt8 *) buffer, bufferSize, &used) == len
      && used <= len)
    {
      buffer[used] = '\0';
      return true;
    }

  return false;
}

Boolean
CFStringGetFileSystemRepresentation (CFStringRef string, char *buffer,
                                     CFIndex maxBufLen)
{
  /* FIXME */
  return CFStringGetCString (string, buffer, maxBufLen,
                             CFStringGetSystemEncoding ());
}


UniChar
CFStringGetCharacterAtIndex (CFStringRef str, CFIndex idx)
{
  CF_OBJC_FUNCDISPATCHV (_kCFStringTypeID, UniChar, str,
                         "characterAtIndex:", idx);
  return CFStringIsUnicode (str) ? ((UniChar *) str->_contents)[idx] :
    ((UInt8 *) str->_contents)[idx];
}

CFIndex
CFStringGetLength (CFStringRef str)
{
  CF_OBJC_FUNCDISPATCHV (_kCFStringTypeID, CFIndex, str, "length");
  return str->_count;
}

CFRange
CFStringGetRangeOfComposedCharactersAtIndex (CFStringRef str,
                                             CFIndex theIndex)
{
  CF_OBJC_FUNCDISPATCHV (_kCFStringTypeID, CFRange, str,
                         "rangeOfComposedCharacterSequenceAtIndex:",
                         theIndex);

  if (CFStringIsUnicode (str))
    {
      CFIndex len = 1;
      UniChar *characters = ((UniChar *) str->_contents) + theIndex;
      if (U16_IS_SURROGATE (*characters))
        {
          len = 2;
          if (U16_IS_SURROGATE_TRAIL (*characters))
            theIndex -= 1;
        }

      return CFRangeMake (theIndex, len);
    }

  return CFRangeMake (theIndex, 1);
}

UTF32Char
CFStringGetLongCharacterForSurrogatePair (UniChar surrogateHigh,
                                          UniChar surrogateLow)
{
  return (UTF32Char) U16_GET_SUPPLEMENTARY (surrogateHigh, surrogateLow);
}

Boolean
CFStringGetSurrogatePairForLongCharacter (UTF32Char character,
                                          UniChar * surrogates)
{
  if (character > 0x10000)
    return false;

  surrogates[0] = U16_LEAD (character);
  surrogates[1] = U16_TRAIL (character);

  return true;
}

Boolean
CFStringIsSurrogateHighCharacter (UniChar character)
{
  return (Boolean) U16_IS_LEAD (character);
}

Boolean
CFStringIsSurrogateLowCharacter (UniChar character)
{
  return (Boolean) U16_IS_TRAIL (character);
}

double
CFStringGetDoubleValue (CFStringRef str)
{
  double d;
  Boolean success;
  CFNumberFormatterRef fmt;

  fmt = CFNumberFormatterCreate (NULL, NULL, kCFNumberFormatterDecimalStyle);
  if (fmt == NULL)
    return 0.0;

  success = CFNumberFormatterGetValueFromString (fmt, str, NULL,
                                                 kCFNumberDoubleType,
                                                 (void *) &d);

  CFRelease (fmt);
  return success ? d : 0.0;
}

SInt32
CFStringGetIntValue (CFStringRef str)
{
  SInt32 i;
  Boolean success;
  CFNumberFormatterRef fmt;

  fmt = CFNumberFormatterCreate (NULL, NULL, kCFNumberFormatterNoStyle);
  if (fmt == NULL)
    return 0;

  success = CFNumberFormatterGetValueFromString (fmt, str, NULL,
                                                 kCFNumberSInt32Type,
                                                 (void *) &i);

  CFRelease (fmt);
  return success ? i : 0;
}



/* CFMutableString functions start here. 
   
   All mutable string instances are Unicode.  This makes it
   easier to use the ICU functions. */

/* This function is used to grow the size of a CFMutableString buffer.
   The string's buffer will grow to (newCapacity * sizeof(UniChar)).
   On return, oldContentBuffer will point to the old data.  If this value
   is not provided, the old content buffer is freed and data will be lost. */
static Boolean
CFStringCheckCapacityAndGrow (CFMutableStringRef str, CFIndex newCapacity,
                              void **oldContentBuffer)
{
  void *currentContents;
  void *newContents;
  struct __CFMutableString *mStr = (struct __CFMutableString *) str;

  if (mStr->_capacity >= newCapacity)
    {
      if (oldContentBuffer)
        *oldContentBuffer = str->_contents;
      return true;
    }

  currentContents = mStr->_contents;

  newContents = CFAllocatorAllocate (mStr->_allocator,
                                     (newCapacity * sizeof (UniChar)), 0);
  if (newContents == NULL)
    return false;
  mStr->_contents = newContents;
  mStr->_capacity = newCapacity;

  if (oldContentBuffer)
    *oldContentBuffer = currentContents;
  else
    CFAllocatorDeallocate (mStr->_allocator, currentContents);

  return true;
}

#define DEFAULT_STRING_CAPACITY 16

#define CFSTRING_INIT_MUTABLE(str) do \
{ \
  ((CFRuntimeBase *)str)->_flags.info = 0xFF \
    & (_kCFStringIsMutable | _kCFStringIsUnicode | _kCFStringHasNullByte); \
} while(0)

CFMutableStringRef
CFStringCreateMutable (CFAllocatorRef alloc, CFIndex maxLength)
{
  struct __CFMutableString *new;

  new = (struct __CFMutableString *) _CFRuntimeCreateInstance (alloc,
                                                               _kCFStringTypeID,
                                                               sizeof (struct
                                                                       __CFMutableString)
                                                               -
                                                               sizeof
                                                               (CFRuntimeBase),
                                                               NULL);

  new->_capacity =
    maxLength < DEFAULT_STRING_CAPACITY ? DEFAULT_STRING_CAPACITY : maxLength;
  new->_allocator = alloc ? alloc : CFAllocatorGetDefault ();
  new->_contents = CFAllocatorAllocate (new->_allocator,
                                        new->_capacity * sizeof (UniChar), 0);

  CFSTRING_INIT_MUTABLE (new);

  return (CFMutableStringRef) new;
}

CFMutableStringRef
CFStringCreateMutableCopy (CFAllocatorRef alloc, CFIndex maxLength,
                           CFStringRef str)
{
  CFMutableStringRef new;
  CFStringInlineBuffer buffer;
  UniChar *contents;
  CFIndex textLen;
  CFIndex capacity;
  CFIndex idx;

  textLen = CFStringGetLength (str);
  capacity = textLen;
  if (maxLength > capacity)
    capacity = maxLength;
  new = (CFMutableStringRef) CFStringCreateMutable (alloc, capacity);

  /* An inline buffer is going to work well here... */
  CFStringInitInlineBuffer (str, &buffer, CFRangeMake (0, textLen));
  contents = (UniChar *) new->_contents;
  idx = 0;
  while (idx < textLen)
    {
      UniChar c = CFStringGetCharacterFromInlineBuffer (&buffer, idx++);
      *(contents++) = c;
    }
  new->_count = textLen;

  CFSTRING_INIT_MUTABLE (new);

  return new;
}

CFMutableStringRef
CFStringCreateMutableWithExternalCharactersNoCopy (CFAllocatorRef alloc,
                                                   UniChar * chars,
                                                   CFIndex numChars,
                                                   CFIndex capacity,
                                                   CFAllocatorRef
                                                   externalCharactersAllocator)
{
  return NULL;                  /* FIXME */
}

void
CFStringSetExternalCharactersNoCopy (CFMutableStringRef str, UniChar * chars,
                                     CFIndex length, CFIndex capacity)
{
  return;                       /* FIXME */
}

CFIndex
CFStringFindAndReplace (CFMutableStringRef str, CFStringRef stringToFind,
                        CFStringRef replacementString, CFRange rangeToSearch,
                        CFOptionFlags compareOptions)
{
  return 0;                     /* FIXME */
}

void
CFStringAppend (CFMutableStringRef str, CFStringRef appendString)
{
  CFStringReplace (str, CFRangeMake (CFStringGetLength (str), 0),
                   appendString);
}

void
CFStringAppendCharacters (CFMutableStringRef str,
                          const UniChar * chars, CFIndex numChars)
{
  if (CF_IS_OBJC (_kCFStringTypeID, str))
    {
      // TODO: add a test for this branch
      CFStringRef wrapped;

      wrapped = CFStringCreateWithCharactersNoCopy (NULL, chars, numChars,
                                                    kCFAllocatorNull);

      CF_OBJC_VOIDCALLV (str, "appendString:", wrapped);

      CFRelease (wrapped);
      return;
    }

  CFIndex length;
  void *contents;

  length = str->_count;

  if (CFStringCheckCapacityAndGrow (str, (length + numChars), &contents)
      && contents != str->_contents)
    {
      memcpy (str->_contents, contents, length * sizeof (UniChar));
      CFAllocatorDeallocate (str->_deallocator, contents);
    }

  memcpy ((UniChar *) str->_contents + length, chars,
          numChars * sizeof (UniChar));
  str->_count = length + numChars;
}

void
CFStringAppendCString (CFMutableStringRef str, const char *cStr,
                       CFStringEncoding encoding)
{
  if (CF_IS_OBJC (_kCFStringTypeID, str))
    {
      // TODO: add a test for this branch
      CFStringRef wrapped;

      wrapped = CFStringCreateWithCStringNoCopy (NULL, cStr, encoding,
                                                 kCFAllocatorNull);

      CF_OBJC_VOIDCALLV (str, "appendString:", wrapped);

      CFRelease (wrapped);
      return;
    }

  UniChar b[BUFFER_SIZE];
  UniChar *buffer;
  UniChar *bufferStart;
  const UInt8 *cStrStart;
  const UInt8 *cStrLimit;
  CFIndex numChars;

  buffer = b;
  bufferStart = b;
  cStrStart = (const UInt8 *) cStr;
  cStrLimit = (const UInt8 *) cStr + strlen (cStr);

  numChars = GSUnicodeFromEncoding (&buffer, buffer + BUFFER_SIZE, encoding,
                                    (const UInt8 **) &cStr, cStrLimit, 0);
  if (numChars <= BUFFER_SIZE)
    {
      CFStringAppendCharacters (str, bufferStart, numChars);
    }
  else
    {
      UniChar *tmp;
      UniChar *tmpStart;

      tmp = CFAllocatorAllocate (kCFAllocatorSystemDefault,
                                 numChars * sizeof (UniChar), 0);
      tmpStart = tmp;
      GSUnicodeFromEncoding (&tmp, tmp + numChars, encoding,
                             (const UInt8 **) &cStrStart, cStrLimit, 0);
      CFStringAppendCharacters (str, tmpStart, numChars);
    }
}

void
CFStringAppendFormat (CFMutableStringRef str, CFDictionaryRef options,
                      CFStringRef format, ...)
{
  va_list args;
  va_start (args, format);
  CFStringAppendFormatAndArguments (str, options, format, args);
  va_end (args);
}

void
CFStringAppendFormatAndArguments (CFMutableStringRef str,
                                  CFDictionaryRef options, CFStringRef format,
                                  va_list args)
{
  Boolean free_fmt_str = false;
  CFIndex str_len;
  CFIndex fmt_str_len;
  UniChar buf[BUFFER_SIZE];
  UniChar *fmted_str = buf;
  const UniChar *fmt_str;

  fmt_str_len = CFStringGetLength (format);
  fmt_str = CFStringGetCharactersPtr (format);
  if (fmt_str == 0)
    {
      CFRange range;

      free_fmt_str = true;
      fmt_str = CFAllocatorAllocate (kCFAllocatorSystemDefault,
                                     fmt_str_len * sizeof (UniChar), 0);
      range = CFRangeMake (0, fmt_str_len);
      CFStringGetCharacters (format, range, (UniChar *) fmt_str);
    }
  str_len = GSUnicodeFormatWithArguments (fmted_str, BUFFER_SIZE, options,
                                          fmt_str, fmt_str_len, args);
  if (str_len > BUFFER_SIZE)
    {
      /* The buffer was not long enough for the formatted string, so we will
       * need to allocate a longer buffer and try again.
       */
      fmted_str = CFAllocatorAllocate (kCFAllocatorSystemDefault,
                                       str_len * sizeof (UniChar), 0);
      str_len = GSUnicodeFormatWithArguments (fmted_str, str_len, options,
                                              fmt_str, fmt_str_len, args);

    }
  if (str_len < 0)
    return;

  CFStringAppendCharacters (str, (const UniChar *) fmted_str, str_len);
  if (free_fmt_str)
    CFAllocatorDeallocate (kCFAllocatorSystemDefault, (void *) fmt_str);
  if (fmted_str != buf)
    CFAllocatorDeallocate (kCFAllocatorSystemDefault, str);
}

void
CFStringDelete (CFMutableStringRef str, CFRange range)
{
  CFStringReplace (str, range, CFSTR (""));
}

void
CFStringInsert (CFMutableStringRef str, CFIndex idx, CFStringRef insertedStr)
{
  CFStringReplace (str, CFRangeMake (idx, 0), insertedStr);
}

void
CFStringPad (CFMutableStringRef str, CFStringRef padString,
             CFIndex length, CFIndex indexIntoPad)
{
  if (CF_IS_OBJC (_kCFStringTypeID, str))
    {
      // TODO: add a test for this branch
      CFStringRef padded;

      CF_OBJC_CALLV (CFStringRef, padded, str,
                     "stringByPaddingToLength:withString:startingAtIndex:",
                     length, padString, indexIntoPad);

      CF_OBJC_VOIDCALLV (str, "setString:", padded);

      return;
    }

  if (padString == NULL && length < CFStringGetLength (str))    /* truncating */
    {
      ((UniChar *) str->_contents)[length] = 0x0000;
      str->_count = length;
      str->_hash = 0;
    }
  else
    {
      CFIndex padLength;
      UniChar *padContents;
      UniChar *contents;
      UniChar *end;

      if (!CFStringCheckCapacityAndGrow (str, length, (void **) &contents))
        return;
      if (contents != str->_contents)
        {
          memcpy (str->_contents, contents, length * sizeof (UniChar));
          CFAllocatorDeallocate (str->_deallocator, contents);
        }

      contents = ((UniChar *) str->_contents) + CFStringGetLength (str);
      end = ((UniChar *) str->_contents) + length;

      padLength = CFStringGetLength (padString);
      padContents =
        CFAllocatorAllocate (NULL, padLength * sizeof (UniChar), 0);
      CFStringGetCharacters (padString, CFRangeMake (0, padLength),
                             padContents);

      while (contents < end)
        {
          *contents++ = padContents[indexIntoPad++];
          if (indexIntoPad == padLength)
            indexIntoPad = 0;
        }

      CFAllocatorDeallocate (NULL, padContents);

      str->_count = length;
      str->_hash = 0;
    }
}

void
CFStringReplace (CFMutableStringRef str, CFRange range,
                 CFStringRef replacement)
{
  CF_OBJC_FUNCDISPATCHV (_kCFStringTypeID, void, str,
                         "replaceCharactersInRange:withString:", range,
                         replacement);

  CFStringInlineBuffer buffer;
  CFIndex textLength;
  CFIndex repLength;
  CFIndex idx;
  UniChar *contents;

  textLength = CFStringGetLength (str);
  repLength = CFStringGetLength (replacement);

  if (repLength != range.length)
    {
      UniChar *moveFrom;
      UniChar *moveTo;
      UniChar *oldContents;
      CFIndex newLength;
      CFIndex moveLength;

      newLength = textLength - range.length + repLength;
      if (!CFStringCheckCapacityAndGrow
          (str, newLength, (void **) &oldContents))
        return;
      if (oldContents != str->_contents)
        {
          memcpy (str->_contents, oldContents,
                  range.location * sizeof (UniChar));
        }
      moveFrom = (oldContents + range.location + range.length);
      moveTo = (((UniChar *) str->_contents) + range.location + repLength);
      moveLength = textLength - (range.location + range.length);
      memmove (moveTo, moveFrom, moveLength * sizeof (UniChar));

      if (oldContents != str->_contents)
        CFAllocatorDeallocate (str->_deallocator, (void *) oldContents);

      textLength = newLength;
    }

  CFStringInitInlineBuffer (replacement, &buffer, CFRangeMake (0, repLength));
  contents = (((UniChar *) str->_contents) + range.location);
  idx = 0;
  while (idx < repLength)
    {
      UniChar c = CFStringGetCharacterFromInlineBuffer (&buffer, idx++);
      *(contents++) = c;
    }
  str->_count = textLength;
  str->_hash = 0;
}

void
CFStringReplaceAll (CFMutableStringRef theString, CFStringRef replacement)
{
  CF_OBJC_FUNCDISPATCHV (_kCFStringTypeID, void, theString, "setString:",
                         replacement);

  CFStringInlineBuffer buffer;
  CFIndex textLength;
  CFIndex idx;
  UniChar *contents;

  /* This function is very similar to CFStringReplace() but takes a few
     shortcuts and should be a little fast if all you need to do is replace
     the whole string. */
  textLength = CFStringGetLength (replacement);
  if (!CFStringCheckCapacityAndGrow (theString, textLength + 1, NULL))
    return;

  CFStringInitInlineBuffer (replacement, &buffer,
                            CFRangeMake (0, textLength));
  contents = (UniChar *) theString->_contents;
  idx = 0;
  while (idx < textLength)
    {
      UniChar c = CFStringGetCharacterFromInlineBuffer (&buffer, idx++);
      *(contents++) = c;
    }
  theString->_count = textLength;
  theString->_hash = 0;
}

void
CFStringTrim (CFMutableStringRef str, CFStringRef trimString)
{
  CFStringFindAndReplace (str, trimString, NULL,
                          CFRangeMake (0, CFStringGetLength (str)),
                          kCFCompareAnchored);
  CFStringFindAndReplace (str, trimString, NULL,
                          CFRangeMake (0, CFStringGetLength (str)),
                          kCFCompareBackwards | kCFCompareAnchored);
}

void
CFStringTrimWhitespace (CFMutableStringRef str)
{
  CF_OBJC_FUNCDISPATCHV (_kCFStringTypeID, void, str, "_cfTrimWhitespace");

  CFStringInlineBuffer buffer;
  CFIndex start;
  CFIndex end;
  CFIndex textLength;
  CFIndex newLength;
  CFIndex idx;
  UniChar c;
  UniChar *contents;
  UniChar *contentsStart;

  /* I assume that the resulting string will be shorter than the original
     so no bounds checking is done. */
  textLength = CFStringGetLength (str);
  CFStringInitInlineBuffer (str, &buffer, CFRangeMake (0, textLength));

  idx = 0;
  c = CFStringGetCharacterFromInlineBuffer (&buffer, idx++);
  while (GSCharacterIsWhitespace (c) && idx < textLength)
    c = CFStringGetCharacterFromInlineBuffer (&buffer, idx++);
  start = idx - 1;
  end = start;
  while (idx < textLength)
    {
      c = CFStringGetCharacterFromInlineBuffer (&buffer, idx++);
      /* reset the end point */
      if (!GSCharacterIsWhitespace (c))
        end = idx;
    }

  newLength = end - start;
  contents = (UniChar *) str->_contents;
  contentsStart = (UniChar *) (contents + start);
  memmove (contents, contentsStart, newLength * sizeof (UniChar));

  str->_count = newLength;
  str->_hash = 0;
}

enum
{
  _kCFStringCapitalize,
  _kCFStringLowercase,
  _kCFStringUppercase,
  _kCFStringFold
};

static void
CFStringCaseMap (CFMutableStringRef str, CFLocaleRef locale,
                 CFOptionFlags flags, CFIndex op)
{
#if HAVE_UNICODE_USTRING_H
  char *localeID = NULL;        /* FIXME */
  const UniChar *oldContents;
  CFIndex oldContentsLength;
  CFIndex newLength;
  int32_t optFlags;
  UErrorCode err = U_ZERO_ERROR;
  struct __CFMutableString *mStr = (struct __CFMutableString *) str;

  oldContents = CFStringGetCharactersPtr (str);
  oldContentsLength = CFStringGetLength (str);

  /* Loops a maximum of 2 times, and should never loop more than that.  If
     it does have to go through the loop a 3rd time something is wrong
     and this whole thing will blow up. */
  do
    {
      switch (op)
        {
        case _kCFStringCapitalize:
          newLength = u_strToTitle (mStr->_contents, mStr->_capacity,
                                    oldContents, oldContentsLength, NULL,
                                    localeID, &err);
          break;
        case _kCFStringLowercase:
          newLength = u_strToLower (mStr->_contents, mStr->_capacity,
                                    oldContents, oldContentsLength, localeID,
                                    &err);
          break;
        case _kCFStringUppercase:
          newLength = u_strToUpper (mStr->_contents, mStr->_capacity,
                                    oldContents, oldContentsLength, localeID,
                                    &err);
          break;
        case _kCFStringFold:
          optFlags = 0;         /* FIXME */
          newLength = u_strFoldCase (mStr->_contents, mStr->_capacity,
                                     oldContents, oldContentsLength, optFlags,
                                     &err);
          break;
        default:
          return;
        }
    }
  while (err == U_BUFFER_OVERFLOW_ERROR
         && CFStringCheckCapacityAndGrow (str, newLength,
                                          (void **) &oldContents));
  if (U_FAILURE (err))
    return;

  mStr->_count = newLength;
  mStr->_hash = 0;

  if (oldContents != mStr->_contents)
    CFAllocatorDeallocate (mStr->_allocator, (void *) oldContents);
#else
  /* FIXME */
#endif
}

void
CFStringCapitalize (CFMutableStringRef str, CFLocaleRef locale)
{
  if (CF_IS_OBJC (_kCFStringTypeID, str))
    {
      CFStringRef mod;
      CF_OBJC_CALLV (CFStringRef, mod, str, "capitalizedString");
      CF_OBJC_VOIDCALLV (str, "setString:", mod);

      CFRelease (mod);
    }
  else
    CFStringCaseMap (str, locale, 0, _kCFStringCapitalize);
}

void
CFStringLowercase (CFMutableStringRef str, CFLocaleRef locale)
{
  if (CF_IS_OBJC (_kCFStringTypeID, str))
    {
      CFStringRef mod;
      CF_OBJC_CALLV (CFStringRef, mod, str, "lowercaseString");
      CF_OBJC_VOIDCALLV (str, "setString:", mod);

      CFRelease (mod);
    }
  else
    CFStringCaseMap (str, locale, 0, _kCFStringLowercase);
}

void
CFStringUppercase (CFMutableStringRef str, CFLocaleRef locale)
{
  if (CF_IS_OBJC (_kCFStringTypeID, str))
    {
      CFStringRef mod;
      CF_OBJC_CALLV (CFStringRef, mod, str, "uppercaseString");
      CF_OBJC_VOIDCALLV (str, "setString:", mod);

      CFRelease (mod);
    }
  else
    CFStringCaseMap (str, locale, 0, _kCFStringUppercase);
}

void
CFStringFold (CFMutableStringRef str, CFOptionFlags flags, CFLocaleRef locale)
{
  if (CF_IS_OBJC (_kCFStringTypeID, str))
    {
      /* CFOptionFlags have the same insensitivity values
       * as NSStringCompareOptions.
       * CFLocaleRef is toll-free bridged*/

      CFStringRef mod;
      CF_OBJC_CALLV (CFStringRef, mod, str,
                     "stringByFoldingWithOptions:locale:", flags, locale);

      CF_OBJC_VOIDCALLV (str, "setString:", mod);
      CFRelease (mod);
    }
  else
    CFStringCaseMap (str, locale, flags, _kCFStringFold);
}

CF_INLINE const UNormalizer2 *
CFToICUNormalizer (CFStringNormalizationForm form, UErrorCode *err)
{
  switch (form)
    {
    case kCFStringNormalizationFormD:
      return unorm2_getNFDInstance(err);
    case kCFStringNormalizationFormKD:
      return unorm2_getNFKDInstance(err);
    case kCFStringNormalizationFormC:
      return unorm2_getNFCInstance(err);
    case kCFStringNormalizationFormKC:
      return unorm2_getNFKCInstance(err);
    default:
      return NULL;
    }
}

void
CFStringNormalize (CFMutableStringRef str, CFStringNormalizationForm theForm)
{
#if !UCONFIG_NO_NORMALIZATION
  UniChar *oldContents;
  CFIndex oldContentsLength;
  CFIndex newLength;
  UNormalizationCheckResult checkResult;
  UErrorCode err = U_ZERO_ERROR;
  struct __CFMutableString *mStr;
  CFMutableStringRef objc = NULL;
  const UNormalizer2 *n2 = CFToICUNormalizer (theForm, &err);
  if (n2 == NULL || U_FAILURE (err))
    return;

  /* Make sure string isn't already normalized.  Use the quick check for
     speed. We still go through the normalization if the quick check does not
     return UNORM_YES. */
  oldContents = (UniChar *) CFStringGetCharactersPtr (str);
  oldContentsLength = CFStringGetLength (str);

  if (oldContents != NULL)
    {
      checkResult =
        unorm2_quickCheck (n2, oldContents, oldContentsLength, &err);
      if (U_FAILURE (err) || checkResult == UNORM_YES)
        return;
    }

  if (CF_IS_OBJC (_kCFStringTypeID, str))
    {
      objc = str;
      str = CFStringCreateMutableCopy (kCFAllocatorDefault, 0, objc);
    }

  /* unorm_normalize requires that source/dest buffers don't overlap */
  mStr = (struct __CFMutableString *) str;
  oldContents = CFAllocatorAllocate (mStr->_allocator,
                                     oldContentsLength * sizeof (UniChar), 0);
  CFStringGetCharacters (str, CFRangeMake (0, oldContentsLength),
                         oldContents);

  /* Works just like CFStringCaseMap() above... */
  do
    {
      newLength = unorm2_normalize (n2, oldContents, oldContentsLength,
                                    mStr->_contents, mStr->_capacity, &err);
    }
  while (err == U_BUFFER_OVERFLOW_ERROR
         && CFStringCheckCapacityAndGrow (str, newLength, NULL));

  if (U_FAILURE (err))
    return;

  mStr->_count = newLength;

  if (oldContents != mStr->_contents)
    CFAllocatorDeallocate (mStr->_allocator, (void *) oldContents);

  if (objc != NULL)
    {
      CF_OBJC_VOIDCALLV (objc, "setString:", str);
      CFRelease (str);
    }
#else
  /* FIXME */
#endif
}

Boolean
CFStringTransform (CFMutableStringRef str, CFRange * range,
                   CFStringRef transform, Boolean reverse)
{
#if !UCONFIG_NO_TRANSLITERATION
#define UTRANS_LENGTH 128
  struct __CFMutableString *mStr;
  UniChar transID[UTRANS_LENGTH];
  CFIndex idLength;
  CFIndex newLength;
  CFIndex start;
  CFIndex limit;
  UTransliterator *utrans;
  UTransDirection dir;
  UErrorCode err = U_ZERO_ERROR;

  dir = reverse ? UTRANS_REVERSE : UTRANS_FORWARD;

  idLength = CFStringGetLength (transform);
  if (idLength > UTRANS_LENGTH)
    idLength = UTRANS_LENGTH;
  CFStringGetCharacters (transform, CFRangeMake (0, idLength), transID);
  utrans = utrans_openU (transID, idLength, dir, NULL, 0, NULL, &err);
  if (U_FAILURE (err))
    return false;

  newLength = CFStringGetLength (str);
  if (range)
    {
      start = range->location;
      limit = range->length + start;
    }
  else
    {
      start = 0;
      limit = newLength;
    }

  if (CF_IS_OBJC (_kCFStringTypeID, str))
    {
      mStr = (struct __CFMutableString *)
        CFStringCreateMutableCopy (kCFAllocatorDefault, 0, str);
    }
  else
    {
      mStr = (struct __CFMutableString *) str;
    }

  utrans_transUChars (utrans, mStr->_contents, (int32_t *) & mStr->_count,
                      mStr->_capacity, start, (int32_t *) & limit, &err);
  utrans_close (utrans);

  if (((CFMutableStringRef) mStr) != str)       /* ObjC case */
    {
      CF_OBJC_VOIDCALLV (str, "setString:", mStr);
      CFRelease (mStr);
    }

  if (U_FAILURE (err))
    return false;

  if (range)
    range->length = limit;

  return true;
#else
  return false;
#endif
}