-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
NSString.swift
1671 lines (1407 loc) · 72 KB
/
NSString.swift
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
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
@_implementationOnly import CoreFoundation
internal import Synchronization
public typealias unichar = UInt16
extension unichar {
public init(unicodeScalarLiteral scalar: UnicodeScalar) {
self.init(scalar.value)
}
}
/// Returns a localized string, using the main bundle if one is not specified.
public
func NSLocalizedString(_ key: String,
tableName: String? = nil,
bundle: Bundle = Bundle.main,
value: String = "",
comment: String) -> String {
return bundle.localizedString(forKey: key, value: value, table: tableName)
}
internal let kCFStringEncodingMacRoman = CFStringBuiltInEncodings.macRoman.rawValue
internal let kCFStringEncodingWindowsLatin1 = CFStringBuiltInEncodings.windowsLatin1.rawValue
internal let kCFStringEncodingISOLatin1 = CFStringBuiltInEncodings.isoLatin1.rawValue
internal let kCFStringEncodingNextStepLatin = CFStringBuiltInEncodings.nextStepLatin.rawValue
internal let kCFStringEncodingASCII = CFStringBuiltInEncodings.ASCII.rawValue
internal let kCFStringEncodingUnicode = CFStringBuiltInEncodings.unicode.rawValue
internal let kCFStringEncodingUTF8 = CFStringBuiltInEncodings.UTF8.rawValue
internal let kCFStringEncodingNonLossyASCII = CFStringBuiltInEncodings.nonLossyASCII.rawValue
internal let kCFStringEncodingUTF16 = CFStringBuiltInEncodings.UTF16.rawValue
internal let kCFStringEncodingUTF16BE = CFStringBuiltInEncodings.UTF16BE.rawValue
internal let kCFStringEncodingUTF16LE = CFStringBuiltInEncodings.UTF16LE.rawValue
internal let kCFStringEncodingUTF32 = CFStringBuiltInEncodings.UTF32.rawValue
internal let kCFStringEncodingUTF32BE = CFStringBuiltInEncodings.UTF32BE.rawValue
internal let kCFStringEncodingUTF32LE = CFStringBuiltInEncodings.UTF32LE.rawValue
internal let kCFStringGraphemeCluster = CFStringCharacterClusterType.graphemeCluster
internal let kCFStringComposedCharacterCluster = CFStringCharacterClusterType.composedCharacterCluster
internal let kCFStringCursorMovementCluster = CFStringCharacterClusterType.cursorMovementCluster
internal let kCFStringBackwardDeletionCluster = CFStringCharacterClusterType.backwardDeletionCluster
internal let kCFStringNormalizationFormD = CFStringNormalizationForm.D
internal let kCFStringNormalizationFormKD = CFStringNormalizationForm.KD
internal let kCFStringNormalizationFormC = CFStringNormalizationForm.C
internal let kCFStringNormalizationFormKC = CFStringNormalizationForm.KC
extension NSString {
public struct EncodingConversionOptions : OptionSet, Sendable {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let allowLossy = EncodingConversionOptions(rawValue: 1)
public static let externalRepresentation = EncodingConversionOptions(rawValue: 2)
internal static let failOnPartialEncodingConversion = EncodingConversionOptions(rawValue: 1 << 20)
}
public struct EnumerationOptions : OptionSet, Sendable {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let byLines = EnumerationOptions([])
public static let byParagraphs = EnumerationOptions(rawValue: 1)
public static let byComposedCharacterSequences = EnumerationOptions(rawValue: 2)
@available(*, unavailable, message: "Enumeration by words isn't supported in swift-corelibs-foundation")
public static let byWords = EnumerationOptions(rawValue: 3)
@available(*, unavailable, message: "Enumeration by sentences isn't supported in swift-corelibs-foundation")
public static let bySentences = EnumerationOptions(rawValue: 4)
public static let reverse = EnumerationOptions(rawValue: 1 << 8)
public static let substringNotRequired = EnumerationOptions(rawValue: 1 << 9)
public static let localized = EnumerationOptions(rawValue: 1 << 10)
internal static let forceFullTokens = EnumerationOptions(rawValue: 1 << 20)
}
}
extension NSString {
public typealias CompareOptions = String.CompareOptions
}
extension NSString.CompareOptions {
internal func _cfValue(_ fixLiteral: Bool = false) -> CFStringCompareFlags {
return contains(.literal) || !fixLiteral ? CFStringCompareFlags(rawValue: rawValue) : CFStringCompareFlags(rawValue: rawValue).union(.compareNonliteral)
}
}
public struct StringTransform: Equatable, Hashable, RawRepresentable, Sendable {
typealias RawType = String
public let rawValue: String
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public init(rawValue: String) {
self.rawValue = rawValue
}
// Transliteration
public static let toLatin = StringTransform(rawValue: kCFStringTransformToLatin!._swiftObject)
public static let latinToArabic = StringTransform(rawValue: kCFStringTransformLatinArabic!._swiftObject)
public static let latinToCyrillic = StringTransform(rawValue: kCFStringTransformLatinCyrillic!._swiftObject)
public static let latinToGreen = StringTransform(rawValue: kCFStringTransformLatinGreek!._swiftObject)
public static let latinToHangul = StringTransform(rawValue: kCFStringTransformLatinHangul!._swiftObject)
public static let latinToHebrew = StringTransform(rawValue: kCFStringTransformLatinHebrew!._swiftObject)
public static let latinToHiragana = StringTransform(rawValue: kCFStringTransformLatinHiragana!._swiftObject)
public static let latinToKatakana = StringTransform(rawValue: kCFStringTransformLatinKatakana!._swiftObject)
public static let latinToThai = StringTransform(rawValue: kCFStringTransformLatinThai!._swiftObject)
public static let hiraganaToKatakana = StringTransform(rawValue: kCFStringTransformHiraganaKatakana!._swiftObject)
public static let mandarinToLatin = StringTransform(rawValue: kCFStringTransformMandarinLatin!._swiftObject)
// Diacritic and Combining Mark Removal
public static let stripDiacritics = StringTransform(rawValue: kCFStringTransformStripDiacritics!._swiftObject)
public static let stripCombiningMarks = StringTransform(rawValue: kCFStringTransformStripCombiningMarks!._swiftObject)
// Halfwidth and Fullwidth Form Conversion
public static let fullwidthToHalfwidth = StringTransform(rawValue: kCFStringTransformFullwidthHalfwidth!._swiftObject)
// Character Representation
public static let toUnicodeName = StringTransform(rawValue: kCFStringTransformToUnicodeName!._swiftObject)
public static let toXMLHex = StringTransform(rawValue: kCFStringTransformToXMLHex!._swiftObject)
}
// NSCache is marked as non-Sendable, but it actually does have locking in our implementation
fileprivate nonisolated(unsafe) let regularExpressionCache: NSCache<NSString, NSRegularExpression> = {
let cache = NSCache<NSString, NSRegularExpression>()
cache.name = "NSRegularExpressionCache"
cache.countLimit = 10
return cache
}()
internal func _createRegexForPattern(_ pattern: String, _ options: NSRegularExpression.Options) -> NSRegularExpression? {
let key = "\(options):\(pattern)"
if let regex = regularExpressionCache.object(forKey: key._nsObject) {
return regex
}
guard let regex = try? NSRegularExpression(pattern: pattern, options: options) else {
return nil
}
regularExpressionCache.setObject(regex, forKey: key._nsObject)
return regex
}
internal func _bytesInEncoding(_ str: NSString, _ encoding: String.Encoding, _ fatalOnError: Bool, _ externalRep: Bool, _ lossy: Bool) -> UnsafePointer<Int8>? {
let theRange = NSRange(location: 0, length: str.length)
var cLength = 0
var used = 0
var options: NSString.EncodingConversionOptions = []
if externalRep {
options.formUnion(.externalRepresentation)
}
if lossy {
options.formUnion(.allowLossy)
}
if !str.getBytes(nil, maxLength: Int.max - 1, usedLength: &cLength, encoding: encoding.rawValue, options: options, range: theRange, remaining: nil) {
if fatalOnError {
fatalError("Conversion on encoding failed")
}
return nil
}
let buffer = malloc(cLength + 1)!.bindMemory(to: Int8.self, capacity: cLength + 1)
if !str.getBytes(buffer, maxLength: cLength, usedLength: &used, encoding: encoding.rawValue, options: options, range: theRange, remaining: nil) {
fatalError("Internal inconsistency; previously claimed getBytes returned success but failed with similar invocation")
}
buffer.advanced(by: cLength).initialize(to: 0)
return UnsafePointer(buffer) // leaked and should be autoreleased via a NSData backing but we cannot here
}
internal func isALineSeparatorTypeCharacter(_ ch: unichar) -> Bool {
if ch > 0x0d && ch < 0x0085 { /* Quick test to cover most chars */
return false
}
return ch == 0x0a || ch == 0x0d || ch == 0x0085 || ch == 0x2028 || ch == 0x2029
}
internal func isAParagraphSeparatorTypeCharacter(_ ch: unichar) -> Bool {
if ch > 0x0d && ch < 0x2029 { /* Quick test to cover most chars */
return false
}
return ch == 0x0a || ch == 0x0d || ch == 0x2029
}
@available(*, unavailable)
extension NSString : @unchecked Sendable { }
open class NSString : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding {
private let _cfinfo = _CFInfo(typeID: CFStringGetTypeID())
internal var _storage: String
open var length: Int {
guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else {
NSRequiresConcreteImplementation()
}
return _storage.utf16.count
}
open func character(at index: Int) -> unichar {
guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else {
NSRequiresConcreteImplementation()
}
let start = _storage.utf16.startIndex
return _storage.utf16[_storage.utf16.index(start, offsetBy: index)]
}
public override convenience init() {
self.init("")
}
internal init(_ string: String) {
_storage = string
}
public convenience required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.string") {
let str = aDecoder._decodePropertyListForKey("NS.string") as! String
self.init(string: str)
} else {
let decodedData : Data? = aDecoder.withDecodedUnsafeBufferPointer(forKey: "NS.bytes") {
guard let buffer = $0 else { return nil }
return Data(buffer: buffer)
}
guard let data = decodedData else { return nil }
self.init(data: data, encoding: String.Encoding.utf8.rawValue)
}
}
public required convenience init(string aString: String) {
self.init(aString)
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSString.self {
return self
}
let characters = UnsafeMutablePointer<unichar>.allocate(capacity: length)
getCharacters(characters, range: NSRange(location: 0, length: length))
let result = NSString(characters: characters, length: length)
characters.deinitialize(count: length)
characters.deallocate()
return result
}
open override func mutableCopy() -> Any {
return mutableCopy(with: nil)
}
open func mutableCopy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSString.self || type(of: self) === NSMutableString.self {
if let contents = _fastContents {
return NSMutableString(characters: contents, length: length)
}
}
let characters = UnsafeMutablePointer<unichar>.allocate(capacity: length)
getCharacters(characters, range: NSRange(location: 0, length: length))
let result = NSMutableString(characters: characters, length: length)
characters.deinitialize(count: 1)
characters.deallocate()
return result
}
public static var supportsSecureCoding: Bool {
return true
}
open func encode(with aCoder: NSCoder) {
if let aKeyedCoder = aCoder as? NSKeyedArchiver {
aKeyedCoder._encodePropertyList(self, forKey: "NS.string")
} else {
aCoder.encode(self)
}
}
public init(characters: UnsafePointer<unichar>, length: Int) {
_storage = String(decoding: UnsafeBufferPointer(start: characters, count: length), as: UTF16.self)
}
public required convenience init(unicodeScalarLiteral value: StaticString) {
self.init(stringLiteral: value)
}
public required convenience init(extendedGraphemeClusterLiteral value: StaticString) {
self.init(stringLiteral: value)
}
public required init(stringLiteral value: StaticString) {
_storage = String(describing: value)
}
public convenience init?(cString nullTerminatedCString: UnsafePointer<Int8>, encoding: UInt) {
guard let str =
CFStringCreateWithCString(kCFAllocatorSystemDefault,
nullTerminatedCString,
CFStringConvertNSStringEncodingToEncoding(numericCast(encoding))) else {
return nil
}
self.init(string: str._swiftObject)
}
internal func _fastCStringContents(_ nullTerminated: Bool) -> UnsafePointer<Int8>? {
// There is no truly safe way to return an inner pointer for CFString here
return nil
}
internal var _fastContents: UnsafePointer<UniChar>? {
// The string held in _storage is a Swift string, natively stored as UTF-8. There is no UTF-16 data that can be
// returned here. If, in the future, CFStrings are lazy-bridged to Swift Strings and the address of the CFString
// is held as a foreign object in the String then it may be possible to return a pointer here.
return nil
}
internal var _encodingCantBeStoredInEightBitCFString: Bool {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
return !_storage._guts._isContiguousASCII
}
return false
}
internal override var _cfTypeID: CFTypeID {
return CFStringGetTypeID()
}
open override func isEqual(_ object: Any?) -> Bool {
guard let string = (object as? NSString)?._swiftObject else { return false }
return self.isEqual(to: string)
}
open override var description: String {
return _swiftObject
}
open override var hash: Int {
return Int(bitPattern:CFStringHashNSString(self._cfObject))
}
}
extension NSString {
public func getCharacters(_ buffer: UnsafeMutablePointer<unichar>, range: NSRange) {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
let utf16 = _storage.utf16
var idx = utf16.index(utf16.startIndex, offsetBy: range.location)
for offset in 0..<range.length {
buffer[offset] = utf16[idx]
idx = utf16.index(after: idx)
}
} else {
//TODO: fast paths for _fastContents != nil / _fastCString != nil
for idx in 0..<range.length {
buffer[idx] = character(at: idx + range.location)
}
}
}
public func substring(from: Int) -> String {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
return String(_storage.utf16.suffix(from: _storage.utf16.index(_storage.utf16.startIndex, offsetBy: from)))!
} else {
return substring(with: NSRange(location: from, length: length - from))
}
}
public func substring(to: Int) -> String {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
return String(_storage.utf16.prefix(upTo: _storage.utf16.index(_storage.utf16.startIndex, offsetBy: to)))!
} else {
return substring(with: NSRange(location: 0, length: to))
}
}
public func substring(with range: NSRange) -> String {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
let start = _storage.utf16.startIndex
let min = _storage.utf16.index(start, offsetBy: range.location)
let max = _storage.utf16.index(min, offsetBy: range.length)
return String(decoding: _storage.utf16[min..<max], as: UTF16.self)
} else {
let buff = UnsafeMutablePointer<unichar>.allocate(capacity: range.length)
getCharacters(buff, range: range)
let result = String(utf16CodeUnits: buff, count: range.length)
buff.deinitialize(count: 1)
buff.deallocate()
return result
}
}
public func compare(_ string: String) -> ComparisonResult {
return compare(string, options: [], range: NSRange(location: 0, length: length))
}
public func compare(_ string: String, options mask: CompareOptions) -> ComparisonResult {
return compare(string, options: mask, range: NSRange(location: 0, length: length))
}
public func compare(_ string: String, options mask: CompareOptions, range compareRange: NSRange) -> ComparisonResult {
return compare(string, options: mask, range: compareRange, locale: nil)
}
public func compare(_ string: String, options mask: CompareOptions, range compareRange: NSRange, locale: Any?) -> ComparisonResult {
var res: CFComparisonResult
if let loc = locale {
res = CFStringCompareWithOptionsAndLocale(_cfObject, string._cfObject, CFRange(compareRange), mask._cfValue(true), (loc as! NSLocale)._cfObject)
} else {
res = CFStringCompareWithOptionsAndLocale(_cfObject, string._cfObject, CFRange(compareRange), mask._cfValue(true), nil)
}
return ComparisonResult._fromCF(res)
}
public func caseInsensitiveCompare(_ string: String) -> ComparisonResult {
return compare(string, options: .caseInsensitive, range: NSRange(location: 0, length: length))
}
public func localizedCompare(_ string: String) -> ComparisonResult {
return compare(string, options: [], range: NSRange(location: 0, length: length), locale: Locale.current._bridgeToObjectiveC())
}
public func localizedCaseInsensitiveCompare(_ string: String) -> ComparisonResult {
return compare(string, options: .caseInsensitive, range: NSRange(location: 0, length: length), locale: Locale.current._bridgeToObjectiveC())
}
public func localizedStandardCompare(_ string: String) -> ComparisonResult {
return compare(string, options: [.caseInsensitive, .numeric, .widthInsensitive, .forcedOrdering], range: NSRange(location: 0, length: length), locale: Locale.current._bridgeToObjectiveC())
}
public func isEqual(to aString: String) -> Bool {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
return _storage == aString
} else {
return length == aString.length && compare(aString, options: .literal, range: NSRange(location: 0, length: length)) == .orderedSame
}
}
public func hasPrefix(_ str: String) -> Bool {
return range(of: str, options: .anchored, range: NSRange(location: 0, length: length)).location != NSNotFound
}
public func hasSuffix(_ str: String) -> Bool {
return range(of: str, options: [.anchored, .backwards], range: NSRange(location: 0, length: length)).location != NSNotFound
}
public func commonPrefix(with str: String, options mask: CompareOptions = []) -> String {
let receiver = self as String
if receiver.isEmpty || str.isEmpty {
return ""
}
let literal = mask.contains(.literal)
let caseInsensitive = mask.contains(.caseInsensitive)
var result = ""
var otherIterator = str.makeIterator()
for ch in receiver {
guard let otherCh = otherIterator.next() else { break }
if ch != otherCh {
guard caseInsensitive && String(ch).lowercased() == String(otherCh).lowercased() else { break }
}
if literal && otherCh.unicodeScalars.count != ch.unicodeScalars.count { break }
result.append(ch)
}
return result
}
public func contains(_ str: String) -> Bool {
return range(of: str, options: [], range: NSRange(location: 0, length: length), locale: nil).location != NSNotFound
}
public func localizedCaseInsensitiveContains(_ str: String) -> Bool {
return range(of: str, options: .caseInsensitive, range: NSRange(location: 0, length: length), locale: Locale.current).location != NSNotFound
}
public func localizedStandardContains(_ str: String) -> Bool {
return range(of: str, options: [.caseInsensitive, .diacriticInsensitive], range: NSRange(location: 0, length: length), locale: Locale.current).location != NSNotFound
}
public func localizedStandardRange(of str: String) -> NSRange {
return range(of: str, options: [.caseInsensitive, .diacriticInsensitive], range: NSRange(location: 0, length: length), locale: Locale.current)
}
public func range(of searchString: String) -> NSRange {
return range(of: searchString, options: [], range: NSRange(location: 0, length: length), locale: nil)
}
public func range(of searchString: String, options mask: CompareOptions = []) -> NSRange {
return range(of: searchString, options: mask, range: NSRange(location: 0, length: length), locale: nil)
}
public func range(of searchString: String, options mask: CompareOptions = [], range searchRange: NSRange) -> NSRange {
return range(of: searchString, options: mask, range: searchRange, locale: nil)
}
internal func _rangeOfRegularExpressionPattern(regex pattern: String, options mask: CompareOptions, range searchRange: NSRange, locale: Locale?) -> NSRange {
var matchedRange = NSRange(location: NSNotFound, length: 0)
let regexOptions: NSRegularExpression.Options = mask.contains(.caseInsensitive) ? .caseInsensitive : []
let matchingOptions: NSRegularExpression.MatchingOptions = mask.contains(.anchored) ? .anchored : []
if let regex = _createRegexForPattern(pattern, regexOptions) {
matchedRange = regex.rangeOfFirstMatch(in: _swiftObject, options: matchingOptions, range: searchRange)
}
return matchedRange
}
public func range(of searchString: String, options mask: CompareOptions = [], range searchRange: NSRange, locale: Locale?) -> NSRange {
let findStrLen = searchString.length
let len = length
precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Bounds Range {\(searchRange.location), \(searchRange.length)} out of bounds; string length \(len)")
if mask.contains(.regularExpression) {
return _rangeOfRegularExpressionPattern(regex: searchString, options: mask, range:searchRange, locale: locale)
}
if searchRange.length == 0 || findStrLen == 0 { // ??? This last item can't be here for correct Unicode compares
return NSRange(location: NSNotFound, length: 0)
}
var result = CFRange()
let res = withUnsafeMutablePointer(to: &result) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in
if let loc = locale {
return CFStringFindWithOptionsAndLocale(_cfObject, searchString._cfObject, CFRange(searchRange), mask._cfValue(true), loc._cfObject, rangep)
} else {
return CFStringFindWithOptionsAndLocale(_cfObject, searchString._cfObject, CFRange(searchRange), mask._cfValue(true), nil, rangep)
}
}
if res {
return NSRange(location: result.location, length: result.length)
} else {
return NSRange(location: NSNotFound, length: 0)
}
}
public func rangeOfCharacter(from searchSet: CharacterSet) -> NSRange {
return rangeOfCharacter(from: searchSet, options: [], range: NSRange(location: 0, length: length))
}
public func rangeOfCharacter(from searchSet: CharacterSet, options mask: CompareOptions = []) -> NSRange {
return rangeOfCharacter(from: searchSet, options: mask, range: NSRange(location: 0, length: length))
}
public func rangeOfCharacter(from searchSet: CharacterSet, options mask: CompareOptions = [], range searchRange: NSRange) -> NSRange {
let len = length
precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Bounds Range {\(searchRange.location), \(searchRange.length)} out of bounds; string length \(len)")
var result = CFRange()
let res = withUnsafeMutablePointer(to: &result) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in
return CFStringFindCharacterFromSet(_cfObject, searchSet._cfObject, CFRange(searchRange), mask._cfValue(), rangep)
}
if res {
return NSRange(location: result.location, length: result.length)
} else {
return NSRange(location: NSNotFound, length: 0)
}
}
public func rangeOfComposedCharacterSequence(at index: Int) -> NSRange {
let range = CFStringGetRangeOfCharacterClusterAtIndex(_cfObject, index, kCFStringComposedCharacterCluster)
return NSRange(location: range.location, length: range.length)
}
public func rangeOfComposedCharacterSequences(for range: NSRange) -> NSRange {
let length = self.length
var start: Int
var end: Int
if range.location == length {
start = length
} else {
start = rangeOfComposedCharacterSequence(at: range.location).location
}
var endOfRange = NSMaxRange(range)
if endOfRange == length {
end = length
} else {
if range.length > 0 {
endOfRange = endOfRange - 1 // We want 0-length range to be treated same as 1-length range.
}
end = NSMaxRange(rangeOfComposedCharacterSequence(at: endOfRange))
}
return NSRange(location: start, length: end - start)
}
public func appending(_ aString: String) -> String {
return _swiftObject + aString
}
public var doubleValue: Double {
var start: Int = 0
var result = 0.0
let _ = _swiftObject.scan(CharacterSet.whitespaces, locale: nil, locationToScanFrom: &start) { (value: Double) -> Void in
result = value
}
return result
}
public var floatValue: Float {
var start: Int = 0
var result: Float = 0.0
let _ = _swiftObject.scan(CharacterSet.whitespaces, locale: nil, locationToScanFrom: &start) { (value: Float) -> Void in
result = value
}
return result
}
public var intValue: Int32 {
return Scanner(string: _swiftObject).scanInt32() ?? 0
}
public var integerValue: Int {
let scanner = Scanner(string: _swiftObject)
var value: Int = 0
let _ = scanner.scanInt(&value)
return value
}
public var longLongValue: Int64 {
return Scanner(string: _swiftObject).scanInt64() ?? 0
}
public var boolValue: Bool {
let scanner = Scanner(string: _swiftObject)
// skip initial whitespace if present
let _ = scanner.scanCharacters(from: .whitespaces)
if scanner.scanCharacters(from: CharacterSet(charactersIn: "tTyY")) != nil {
return true
}
// scan a single optional '+' or '-' character, followed by zeroes
if scanner.scanString("+") == nil {
let _ = scanner.scanString("-")
}
// scan any following zeroes
let _ = scanner.scanCharacters(from: CharacterSet(charactersIn: "0"))
return scanner.scanCharacters(from: CharacterSet(charactersIn: "123456789")) != nil
}
public var uppercased: String {
return uppercased(with: nil)
}
public var lowercased: String {
return lowercased(with: nil)
}
public var capitalized: String {
return capitalized(with: nil)
}
public var localizedUppercase: String {
return uppercased(with: Locale.current)
}
public var localizedLowercase: String {
return lowercased(with: Locale.current)
}
public var localizedCapitalized: String {
return capitalized(with: Locale.current)
}
public func uppercased(with locale: Locale?) -> String {
let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)!
CFStringUppercase(mutableCopy, locale?._cfObject)
return mutableCopy._swiftObject
}
public func lowercased(with locale: Locale?) -> String {
let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)!
CFStringLowercase(mutableCopy, locale?._cfObject)
return mutableCopy._swiftObject
}
public func capitalized(with locale: Locale?) -> String {
let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)!
CFStringCapitalize(mutableCopy, locale?._cfObject)
return mutableCopy._swiftObject
}
internal func _getBlockStart(_ startPtr: UnsafeMutablePointer<Int>?, end endPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, forRange range: NSRange, stopAtLineSeparators line: Bool) {
let len = length
var ch: unichar
precondition(range.length <= len && range.location <= len - range.length, "Range {\(range.location), \(range.length)} is out of bounds of length \(len)")
if range.location == 0 && range.length == len && contentsEndPtr == nil { // This occurs often
startPtr?.pointee = 0
endPtr?.pointee = range.length
return
}
/* Find the starting point first */
if let startPtr = startPtr {
var start: Int = 0
if range.location == 0 {
start = 0
} else {
var buf = _NSStringBuffer(string: self, start: range.location, end: len)
/* Take care of the special case where start happens to fall right between \r and \n */
ch = buf.currentCharacter
buf.rewind()
if ch == 0x0a && buf.currentCharacter == 0x0d {
buf.rewind()
}
while true {
if line ? isALineSeparatorTypeCharacter(buf.currentCharacter) : isAParagraphSeparatorTypeCharacter(buf.currentCharacter) {
start = buf.location + 1
break
} else if buf.location <= 0 {
start = 0
break
} else {
buf.rewind()
}
}
startPtr.pointee = start
}
}
if (endPtr != nil || contentsEndPtr != nil) {
var endOfContents = 1
var lineSeparatorLength = 1
var buf = _NSStringBuffer(string: self, start: NSMaxRange(range) - (range.length > 0 ? 1 : 0), end: len)
/* First look at the last char in the range (if the range is zero length, the char after the range) to see if we're already on or within a end of line sequence... */
ch = buf.currentCharacter
if ch == 0x0a {
endOfContents = buf.location
buf.rewind()
if buf.currentCharacter == 0x0d {
lineSeparatorLength = 2
endOfContents -= 1
}
} else {
while true {
if line ? isALineSeparatorTypeCharacter(ch) : isAParagraphSeparatorTypeCharacter(ch) {
endOfContents = buf.location /* This is actually end of contentsRange */
buf.advance() /* OK for this to go past the end */
if ch == 0x0d && buf.currentCharacter == 0x0a {
lineSeparatorLength = 2
}
break
} else if buf.location == len {
endOfContents = len
lineSeparatorLength = 0
break
} else {
buf.advance()
ch = buf.currentCharacter
}
}
}
contentsEndPtr?.pointee = endOfContents
endPtr?.pointee = endOfContents + lineSeparatorLength
}
}
public func getLineStart(_ startPtr: UnsafeMutablePointer<Int>?, end lineEndPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, for range: NSRange) {
_getBlockStart(startPtr, end: lineEndPtr, contentsEnd: contentsEndPtr, forRange: range, stopAtLineSeparators: true)
}
public func lineRange(for range: NSRange) -> NSRange {
var start = 0
var lineEnd = 0
getLineStart(&start, end: &lineEnd, contentsEnd: nil, for: range)
return NSRange(location: start, length: lineEnd - start)
}
public func getParagraphStart(_ startPtr: UnsafeMutablePointer<Int>?, end parEndPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, for range: NSRange) {
_getBlockStart(startPtr, end: parEndPtr, contentsEnd: contentsEndPtr, forRange: range, stopAtLineSeparators: false)
}
public func paragraphRange(for range: NSRange) -> NSRange {
var start = 0
var parEnd = 0
getParagraphStart(&start, end: &parEnd, contentsEnd: nil, for: range)
return NSRange(location: start, length: parEnd - start)
}
private enum EnumerateBy : Sendable {
case lines
case paragraphs
case composedCharacterSequences
init?(parsing options: EnumerationOptions) {
var me: EnumerateBy?
// We don't test for .byLines because .byLines.rawValue == 0, which unfortunately means _every_ NSString.EnumerationOptions contains .byLines.
// Instead, we just default to .lines below.
if options.contains(.byParagraphs) {
guard me == nil else { return nil }
me = .paragraphs
}
if options.contains(.byComposedCharacterSequences) {
guard me == nil else { return nil }
me = .composedCharacterSequences
}
self = me ?? .lines
}
}
public func enumerateSubstrings(in range: NSRange, options opts: EnumerationOptions = [], using block: (String?, NSRange, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) {
guard let enumerateBy = EnumerateBy(parsing: opts) else {
fatalError("You must specify only one of the .by… enumeration options.")
}
// We do not heed the .localized flag because it affects only by-words and by-sentences enumeration, which we do not support in s-c-f.
var currentIndex = opts.contains(.reverse) ? length - 1 : 0
func shouldContinue() -> Bool {
opts.contains(.reverse) ? currentIndex >= 0 : currentIndex < length
}
let reverse = opts.contains(.reverse)
func nextIndex(after fullRange: NSRange, compensatingForLengthDifferenceFrom oldLength: Int) -> Int {
var index = reverse ? fullRange.location - 1 : fullRange.location + fullRange.length
if !reverse {
index += (oldLength - length)
}
return index
}
while shouldContinue() {
var range = NSRange(location: currentIndex, length: 0)
var fullRange = range
switch enumerateBy {
case .lines:
var start = 0, end = 0, contentsEnd = 0
getLineStart(&start, end: &end, contentsEnd: &contentsEnd, for: range)
range.location = start
range.length = contentsEnd - start
fullRange.location = start
fullRange.length = end - start
case .paragraphs:
var start = 0, end = 0, contentsEnd = 0
getParagraphStart(&start, end: &end, contentsEnd: &contentsEnd, for: range)
range.location = start
range.length = contentsEnd - start
fullRange.location = start
fullRange.length = end - start
case .composedCharacterSequences:
range = rangeOfComposedCharacterSequences(for: range)
fullRange = range
}
var substring: String?
if !opts.contains(.substringNotRequired) {
substring = self.substring(with: range)
}
let oldLength = length
var stop: ObjCBool = false
block(substring, range, fullRange, &stop)
if stop.boolValue {
return
}
currentIndex = nextIndex(after: fullRange, compensatingForLengthDifferenceFrom: oldLength)
}
}
public func enumerateLines(_ block: (String, UnsafeMutablePointer<ObjCBool>) -> Void) {
enumerateSubstrings(in: NSRange(location: 0, length: length), options:.byLines) { substr, substrRange, enclosingRange, stop in
block(substr!, stop)
}
}
public var utf8String: UnsafePointer<Int8>? {
return _bytesInEncoding(self, .utf8, false, false, false)
}
public var fastestEncoding: UInt {
return String.Encoding.unicode.rawValue
}
public var smallestEncoding: UInt {
if canBeConverted(to: String.Encoding.ascii.rawValue) {
return String.Encoding.ascii.rawValue
}
return String.Encoding.unicode.rawValue
}
public func data(using encoding: UInt, allowLossyConversion lossy: Bool = false) -> Data? {
let len = length
var reqSize = 0
let cfStringEncoding = CFStringConvertNSStringEncodingToEncoding(numericCast(encoding))
if !CFStringIsEncodingAvailable(cfStringEncoding) {
return nil
}
let convertedLen = __CFStringEncodeByteStream(_cfObject, 0, len, true, cfStringEncoding, lossy ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, nil, 0, &reqSize)
if convertedLen != len {
return nil // Not able to do it all...
}
if 0 < reqSize {
var data = Data(count: reqSize)
data.count = data.withUnsafeMutableBytes { (mutableRawBuffer: UnsafeMutableRawBufferPointer) -> Int in
let mutableBytes = mutableRawBuffer.baseAddress!.assumingMemoryBound(to: UInt8.self)
if __CFStringEncodeByteStream(_cfObject, 0, len, true, cfStringEncoding, lossy ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, mutableBytes, reqSize, &reqSize) == convertedLen {
return reqSize
} else {
fatalError("didn't convert all characters")
}
}
return data
}
return Data()
}
public func data(using encoding: UInt) -> Data? {
return data(using: encoding, allowLossyConversion: false)
}
public func canBeConverted(to encoding: UInt) -> Bool {
if encoding == String.Encoding.unicode.rawValue || encoding == String.Encoding.nonLossyASCII.rawValue || encoding == String.Encoding.utf8.rawValue {
return true
}
return __CFStringEncodeByteStream(_cfObject, 0, length, false,
CFStringConvertNSStringEncodingToEncoding(numericCast(encoding)),
0, nil, 0, nil) == length
}
public func cString(using encoding: UInt) -> UnsafePointer<Int8>? {
return _bytesInEncoding(self, String.Encoding(rawValue: encoding), false, false, false)
}
public func getCString(_ buffer: UnsafeMutablePointer<Int8>, maxLength maxBufferCount: Int, encoding: UInt) -> Bool {
var used = 0
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
if _storage._guts._isContiguousASCII {
used = min(self.length, maxBufferCount - 1)
// This is mutable, but since we just checked the contiguous behavior, should not copy
var copy = _storage
copy.withUTF8 {
$0.withMemoryRebound(to: Int8.self) {
buffer.update(from: $0.baseAddress!, count: used)
}
}
buffer.advanced(by: used).initialize(to: 0)
return true
}
}
if getBytes(UnsafeMutableRawPointer(buffer), maxLength: maxBufferCount, usedLength: &used, encoding: encoding, options: [], range: NSRange(location: 0, length: self.length), remaining: nil) {
buffer.advanced(by: used).initialize(to: 0)
return true
}
return false
}
public func getBytes(_ buffer: UnsafeMutableRawPointer?, maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>?, encoding: UInt, options: EncodingConversionOptions = [], range: NSRange, remaining leftover: NSRangePointer?) -> Bool {
var totalBytesWritten = 0
var numCharsProcessed = 0
let cfStringEncoding =
CFStringConvertNSStringEncodingToEncoding(numericCast(encoding))
var result = true
if length > 0 {
if CFStringIsEncodingAvailable(cfStringEncoding) {