-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNSString.m
More file actions
6537 lines (5955 loc) · 173 KB
/
NSString.m
File metadata and controls
6537 lines (5955 loc) · 173 KB
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
/** 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.