forked from swiftlang/swift-corelibs-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathString.swift
1757 lines (1492 loc) · 58.7 KB
/
String.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
//
//===----------------------------------------------------------------------===//
//
// Exposing the API of NSString on Swift's String
//
//===----------------------------------------------------------------------===//
// Open Issues
// ===========
//
// Property Lists need to be properly bridged
//
func _toNSArray<T, U : AnyObject>(_ a: [T], f: @noescape (T) -> U) -> NSArray {
let result = NSMutableArray(capacity: a.count)
for s in a {
result.add(f(s))
}
return result
}
func _toNSRange(_ r: Range<String.Index>) -> NSRange {
return NSRange(
location: r.lowerBound._utf16Index,
length: r.upperBound._utf16Index - r.lowerBound._utf16Index)
}
func _countFormatSpecifiers(_ a: String) -> Int {
// The implementation takes advantage of the fact that internal
// representation of String is UTF-16. Because we only care about the ASCII
// percent character, we don't need to decode UTF-16.
let percentUTF16 = UTF16.CodeUnit(("%" as UnicodeScalar).value)
let notPercentUTF16: UTF16.CodeUnit = 0
var lastChar = notPercentUTF16 // anything other than % would work here
var count = 0
for c in a.utf16 {
if lastChar == percentUTF16 {
if c == percentUTF16 {
// a "%" following this one should not be taken as literal
lastChar = notPercentUTF16
}
else {
count += 1
lastChar = c
}
} else {
lastChar = c
}
}
return count
}
extension String {
//===--- Bridging Helpers -----------------------------------------------===//
//===--------------------------------------------------------------------===//
/// The corresponding `NSString` - a convenience for bridging code.
var _ns: NSString {
return self._nsObject
}
/// Return an `Index` corresponding to the given offset in our UTF-16
/// representation.
func _index(_ utf16Index: Int) -> Index {
return Index(
String.UTF16View.Index(utf16Index),
within: self
)!
}
/// Return a `Range<Index>` corresponding to the given `NSRange` of
/// our UTF-16 representation.
func _range(_ r: NSRange) -> Range<Index> {
return _index(r.location)..<_index(r.location + r.length)
}
/// Return a `Range<Index>?` corresponding to the given `NSRange` of
/// our UTF-16 representation.
func _optionalRange(_ r: NSRange) -> Range<Index>? {
if r.location == NSNotFound {
return nil
}
return _range(r)
}
/// Invoke `body` on an `Int` buffer. If `index` was converted from
/// non-`nil`, convert the buffer to an `Index` and write it into the
/// memory referred to by `index`
func _withOptionalOutParameter<Result>(
_ index: UnsafeMutablePointer<Index>?,
_ body: @noescape (UnsafeMutablePointer<Int>?) -> Result
) -> Result {
var utf16Index: Int = 0
let result = (index != nil ? body(&utf16Index) : body(nil))
index?.pointee = self._index(utf16Index)
return result
}
/// Invoke `body` on an `NSRange` buffer. If `range` was converted
/// from non-`nil`, convert the buffer to a `Range<Index>` and write
/// it into the memory referred to by `range`
func _withOptionalOutParameter<Result>(
_ range: UnsafeMutablePointer<Range<Index>>?,
_ body: @noescape (UnsafeMutablePointer<NSRange>?) -> Result
) -> Result {
var nsRange = NSRange(location: 0, length: 0)
let result = (range != nil ? body(&nsRange) : body(nil))
range?.pointee = self._range(nsRange)
return result
}
//===--- Class Methods --------------------------------------------------===//
//===--------------------------------------------------------------------===//
// + (const NSStringEncoding *)availableStringEncodings
/// Returns an Array of the encodings string objects support
/// in the application's environment.
public static func availableStringEncodings() -> [Encoding] {
var result = [Encoding]()
var p = NSString.availableStringEncodings()
while p.pointee != 0 {
result.append(Encoding(rawValue: p.pointee))
p += 1
}
return result
}
// + (NSStringEncoding)defaultCStringEncoding
/// Returns the C-string encoding assumed for any method accepting
/// a C string as an argument.
public static func defaultCStringEncoding() -> Encoding {
return Encoding(rawValue: NSString.defaultCStringEncoding())
}
// + (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding
/// Returns a human-readable string giving the name of a given encoding.
public static func localizedName(
of encoding: Encoding
) -> String {
return NSString.localizedName(of: encoding.rawValue)
}
// + (instancetype)localizedStringWithFormat:(NSString *)format, ...
/// Returns a string created by using a given format string as a
/// template into which the remaining argument values are substituted
/// according to the user's default locale.
public static func localizedStringWithFormat(
_ format: String, _ arguments: CVarArg...
) -> String {
return String(format: format, locale: Locale.currentLocale(),
arguments: arguments)
}
//===--------------------------------------------------------------------===//
// NSString factory functions that have a corresponding constructor
// are omitted.
//
// + (instancetype)string
//
// + (instancetype)
// stringWithCharacters:(const unichar *)chars length:(NSUInteger)length
//
// + (instancetype)stringWithFormat:(NSString *)format, ...
//
// + (instancetype)
// stringWithContentsOfFile:(NSString *)path
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfFile:(NSString *)path
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfURL:(NSURL *)url
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfURL:(NSURL *)url
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithCString:(const char *)cString
// encoding:(NSStringEncoding)enc
//===--------------------------------------------------------------------===//
//===--- Adds nothing for String beyond what String(s) does -------------===//
// + (instancetype)stringWithString:(NSString *)aString
//===--------------------------------------------------------------------===//
// + (instancetype)stringWithUTF8String:(const char *)bytes
/// Produces a string created by copying the data from a given
/// C array of UTF8-encoded bytes.
public init?(utf8String bytes: UnsafePointer<CChar>) {
if let ns = NSString(UTF8String: bytes) {
self = ns._swiftObject
} else {
return nil
}
}
//===--- Instance Methods/Properties-------------------------------------===//
//===--------------------------------------------------------------------===//
//===--- Omitted by agreement during API review 5/20/2014 ---------------===//
// @property BOOL boolValue;
// - (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding
/// Returns a Boolean value that indicates whether the
/// `String` can be converted to a given encoding without loss of
/// information.
public func canBeConverted(to encoding: Encoding) -> Bool {
return _ns.canBeConverted(to: encoding.rawValue)
}
// @property NSString* capitalizedString
/// Produce a string with the first character from each word changed
/// to the corresponding uppercase value.
public var capitalized: String {
return _ns.capitalized as String
}
// @property (readonly, copy) NSString *localizedCapitalizedString NS_AVAILABLE(10_11, 9_0);
/// A capitalized representation of the `String` that is produced
/// using the current locale.
public var localizedCapitalized: String {
return _ns.localizedCapitalized
}
// - (NSString *)capitalizedStringWithLocale:(Locale *)locale
/// Returns a capitalized representation of the `String`
/// using the specified locale.
public func capitalized(with locale: Locale?) -> String {
return _ns.capitalized(with: locale) as String
}
// - (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString
/// Returns the result of invoking `compare:options:` with
/// `NSCaseInsensitiveSearch` as the only option.
public func caseInsensitiveCompare(_ aString: String) -> ComparisonResult {
return _ns.caseInsensitiveCompare(aString)
}
//===--- Omitted by agreement during API review 5/20/2014 ---------------===//
// - (unichar)characterAtIndex:(NSUInteger)index
//
// We have a different meaning for "Character" in Swift, and we are
// trying not to expose error-prone UTF-16 integer indexes
// - (NSString *)
// commonPrefixWithString:(NSString *)aString
// options:(StringCompareOptions)mask
/// Returns a string containing characters the `String` and a
/// given string have in common, starting from the beginning of each
/// up to the first characters that aren't equivalent.
public func commonPrefix(
with aString: String, options: CompareOptions = []) -> String {
return _ns.commonPrefix(with: aString, options: options)
}
// - (NSComparisonResult)
// compare:(NSString *)aString
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
// range:(NSRange)range
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
// range:(NSRange)range locale:(id)locale
/// Compares the string using the specified options and
/// returns the lexical ordering for the range.
public func compare(
_ aString: String,
options mask: CompareOptions = [],
range: Range<Index>? = nil,
locale: Locale? = nil
) -> ComparisonResult {
// According to Ali Ozer, there may be some real advantage to
// dispatching to the minimal selector for the supplied options.
// So let's do that; the switch should compile away anyhow.
return locale != nil ? _ns.compare(
aString,
options: mask,
range: _toNSRange(
range ?? self.characters.startIndex..<self.characters.endIndex
),
locale: locale
)
: range != nil ? _ns.compare(
aString,
options: mask,
range: _toNSRange(range!)
)
: !mask.isEmpty ? _ns.compare(aString, options: mask)
: _ns.compare(aString)
}
// - (NSArray *)
// componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
/// Returns an array containing substrings from the `String`
/// that have been divided by characters in a given set.
public func components(separatedBy separator: CharacterSet) -> [String] {
return _ns.components(separatedBy: separator)
}
// - (NSArray *)componentsSeparatedByString:(NSString *)separator
/// Returns an array containing substrings from the `String`
/// that have been divided by a given separator.
public func components(separatedBy separator: String) -> [String] {
return _ns.components(separatedBy: separator)
}
// - (const char *)cStringUsingEncoding:(NSStringEncoding)encoding
/// Returns a representation of the `String` as a C string
/// using a given encoding.
public func cString(using encoding: Encoding) -> [CChar]? {
return withExtendedLifetime(_ns) {
(s: NSString) -> [CChar]? in
_persistCString(s.cString(using: encoding.rawValue))
}
}
// - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding
//
// - (NSData *)
// dataUsingEncoding:(NSStringEncoding)encoding
// allowLossyConversion:(BOOL)flag
/// Returns a `Data` containing a representation of
/// the `String` encoded using a given encoding.
public func data(
using encoding: Encoding,
allowLossyConversion: Bool = false
) -> Data? {
return _ns.data(
using: encoding.rawValue,
allowLossyConversion: allowLossyConversion)
}
// @property NSString* decomposedStringWithCanonicalMapping;
/// Returns a string made by normalizing the `String`'s
/// contents using Form D.
public var decomposedStringWithCanonicalMapping: String {
return _ns.decomposedStringWithCanonicalMapping
}
// @property NSString* decomposedStringWithCompatibilityMapping;
/// Returns a string made by normalizing the `String`'s
/// contents using Form KD.
public var decomposedStringWithCompatibilityMapping: String {
return _ns.decomposedStringWithCompatibilityMapping
}
//===--- Importing Foundation should not affect String printing ---------===//
// Therefore, we're not exposing this:
//
// @property NSString* description
//===--- Omitted for consistency with API review results 5/20/2014 -----===//
// @property double doubleValue;
// - (void)
// enumerateLinesUsing:(void (^)(NSString *line, BOOL *stop))block
/// Enumerates all the lines in a string.
public func enumerateLines(_ body: (line: String, stop: inout Bool) -> ()) {
_ns.enumerateLines {
(line: String, stop: UnsafeMutablePointer<ObjCBool>)
in
var stop_ = false
body(line: line, stop: &stop_)
if stop_ {
UnsafeMutablePointer<ObjCBool>(stop).pointee = true
}
}
}
// - (void)
// enumerateSubstringsInRange:(NSRange)range
// options:(NSStringEnumerationOptions)opts
// usingBlock:(
// void (^)(
// NSString *substring,
// NSRange substringRange,
// NSRange enclosingRange,
// BOOL *stop)
// )block
/// Enumerates the substrings of the specified type in the
/// specified range of the string.
public func enumerateSubstrings(
in range: Range<Index>,
options opts: EnumerationOptions = [],
_ body: (
substring: String?, substringRange: Range<Index>,
enclosingRange: Range<Index>, inout Bool
) -> ()
) {
_ns.enumerateSubstrings(in: _toNSRange(range), options: opts) {
var stop_ = false
body(substring: $0,
substringRange: self._range($1),
enclosingRange: self._range($2),
&stop_)
if stop_ {
UnsafeMutablePointer($3).pointee = true
}
}
}
// @property NSStringEncoding fastestEncoding;
/// Returns the fastest encoding to which the `String` may be
/// converted without loss of information.
public var fastestEncoding: Encoding {
return Encoding(rawValue: _ns.fastestEncoding)
}
// - (const char *)fileSystemRepresentation
/// Returns a file system-specific representation of the `String`.
@available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.")
public var fileSystemRepresentation: [CChar] {
return _persistCString(_ns.fileSystemRepresentation)!
}
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property float floatValue;
// - (BOOL)
// getBytes:(void *)buffer
// maxLength:(NSUInteger)maxBufferCount
// usedLength:(NSUInteger*)usedBufferCount
// encoding:(NSStringEncoding)encoding
// options:(StringEncodingConversionOptions)options
// range:(NSRange)range
// remainingRange:(NSRangePointer)leftover
/// Writes the given `range` of characters into `buffer` in a given
/// `encoding`, without any allocations. Does not NULL-terminate.
///
/// - Parameter buffer: A buffer into which to store the bytes from
/// the receiver. The returned bytes are not NUL-terminated.
///
/// - Parameter maxBufferCount: The maximum number of bytes to write
/// to buffer.
///
/// - Parameter usedBufferCount: The number of bytes used from
/// buffer. Pass `nil` if you do not need this value.
///
/// - Parameter encoding: The encoding to use for the returned bytes.
///
/// - Parameter options: A mask to specify options to use for
/// converting the receiver's contents to `encoding` (if conversion
/// is necessary).
///
/// - Parameter range: The range of characters in the receiver to get.
///
/// - Parameter leftover: The remaining range. Pass `nil` If you do
/// not need this value.
///
/// - Returns: `true` iff some characters were converted.
///
/// - Note: Conversion stops when the buffer fills or when the
/// conversion isn't possible due to the chosen encoding.
///
/// - Note: will get a maximum of `min(buffer.count, maxLength)` bytes.
public func getBytes(
_ buffer: inout [UInt8],
maxLength maxBufferCount: Int,
usedLength usedBufferCount: UnsafeMutablePointer<Int>,
encoding: Encoding,
options: EncodingConversionOptions = [],
range: Range<Index>,
remaining leftover: UnsafeMutablePointer<Range<Index>>
) -> Bool {
return _withOptionalOutParameter(leftover) {
self._ns.getBytes(
&buffer,
maxLength: min(buffer.count, maxBufferCount),
usedLength: usedBufferCount,
encoding: encoding.rawValue,
options: options,
range: _toNSRange(range),
remaining: $0)
}
}
// - (BOOL)
// getCString:(char *)buffer
// maxLength:(NSUInteger)maxBufferCount
// encoding:(NSStringEncoding)encoding
/// Converts the `String`'s content to a given encoding and
/// stores them in a buffer.
/// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes.
public func getCString(
_ buffer: inout [CChar], maxLength: Int, encoding: Encoding
) -> Bool {
return _ns.getCString(&buffer, maxLength: min(buffer.count, maxLength),
encoding: encoding.rawValue)
}
// - (BOOL)
// getFileSystemRepresentation:(char *)buffer
// maxLength:(NSUInteger)maxLength
/// Interprets the `String` as a system-independent path and
/// fills a buffer with a C-string in a format and encoding suitable
/// for use with file-system calls.
/// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes.
@available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.")
public func getFileSystemRepresentation(
_ buffer: inout [CChar], maxLength: Int) -> Bool {
return _ns.getFileSystemRepresentation(
&buffer, maxLength: min(buffer.count, maxLength))
}
// - (void)
// getLineStart:(NSUInteger *)startIndex
// end:(NSUInteger *)lineEndIndex
// contentsEnd:(NSUInteger *)contentsEndIndex
// forRange:(NSRange)aRange
/// Returns by reference the beginning of the first line and
/// the end of the last line touched by the given range.
public func getLineStart(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
for range: Range<Index>
) {
_withOptionalOutParameter(start) {
start in self._withOptionalOutParameter(end) {
end in self._withOptionalOutParameter(contentsEnd) {
contentsEnd in self._ns.getLineStart(
start, end: end,
contentsEnd: contentsEnd,
for: _toNSRange(range))
}
}
}
}
// - (void)
// getParagraphStart:(NSUInteger *)startIndex
// end:(NSUInteger *)endIndex
// contentsEnd:(NSUInteger *)contentsEndIndex
// forRange:(NSRange)aRange
/// Returns by reference the beginning of the first paragraph
/// and the end of the last paragraph touched by the given range.
public func getParagraphStart(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
for range: Range<Index>
) {
_withOptionalOutParameter(start) {
start in self._withOptionalOutParameter(end) {
end in self._withOptionalOutParameter(contentsEnd) {
contentsEnd in self._ns.getParagraphStart(
start, end: end,
contentsEnd: contentsEnd,
for: _toNSRange(range))
}
}
}
}
// - (NSUInteger)hash
/// An unsigned integer that can be used as a hash table address.
public var hash: Int {
return _ns.hash
}
//===--- Already provided by String's core ------------------------------===//
// - (instancetype)init
//===--- Initializers that can fail -------------------------------------===//
// - (instancetype)
// initWithBytes:(const void *)bytes
// length:(NSUInteger)length
// encoding:(NSStringEncoding)encoding
/// Produces an initialized `NSString` object equivalent to the given
/// `bytes` interpreted in the given `encoding`.
public init? <S: Sequence>(bytes: S, encoding: Encoding)
where S.Iterator.Element == UInt8 {
let byteArray = Array(bytes)
if let ns = NSString(
bytes: byteArray, length: byteArray.count, encoding: encoding.rawValue) {
self = ns._swiftObject
} else {
return nil
}
}
// - (instancetype)
// initWithBytesNoCopy:(void *)bytes
// length:(NSUInteger)length
// encoding:(NSStringEncoding)encoding
// freeWhenDone:(BOOL)flag
/// Produces an initialized `String` object that contains a
/// given number of bytes from a given buffer of bytes interpreted
/// in a given encoding, and optionally frees the buffer. WARNING:
/// this initializer is not memory-safe!
public init?(
bytesNoCopy bytes: UnsafeMutablePointer<Void>, length: Int,
encoding: Encoding, freeWhenDone flag: Bool
) {
if let ns = NSString(
bytesNoCopy: bytes, length: length, encoding: encoding.rawValue,
freeWhenDone: flag) {
self = ns._swiftObject
} else {
return nil
}
}
// - (instancetype)
// initWithCharacters:(const unichar *)characters
// length:(NSUInteger)length
/// Returns an initialized `String` object that contains a
/// given number of characters from a given array of Unicode
/// characters.
public init(
utf16CodeUnits: UnsafePointer<unichar>,
count: Int
) {
self = NSString(characters: utf16CodeUnits, length: count)._swiftObject
}
// - (instancetype)
// initWithCharactersNoCopy:(unichar *)characters
// length:(NSUInteger)length
// freeWhenDone:(BOOL)flag
/// Returns an initialized `String` object that contains a given
/// number of characters from a given array of UTF-16 Code Units
public init(
utf16CodeUnitsNoCopy: UnsafePointer<unichar>,
count: Int,
freeWhenDone flag: Bool
) {
self = NSString(
charactersNoCopy: UnsafeMutablePointer(utf16CodeUnitsNoCopy),
length: count,
freeWhenDone: flag)._swiftObject
}
//===--- Initializers that can fail -------------------------------------===//
// - (instancetype)
// initWithContentsOfFile:(NSString *)path
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
/// Produces a string created by reading data from the file at a
/// given path interpreted using a given encoding.
public init(
contentsOfFile path: String,
encoding enc: Encoding
) throws {
let ns = try NSString(contentsOfFile: path, encoding: enc.rawValue)
self = ns._swiftObject
}
// - (instancetype)
// initWithContentsOfFile:(NSString *)path
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
/// Produces a string created by reading data from the file at
/// a given path and returns by reference the encoding used to
/// interpret the file.
public init(
contentsOfFile path: String,
usedEncoding: inout Encoding
) throws {
var enc: UInt = 0
let ns = try NSString(contentsOfFile: path, usedEncoding: &enc)
usedEncoding = Encoding(rawValue: enc)
self = ns._swiftObject
}
public init(
contentsOfFile path: String
) throws {
let ns = try NSString(contentsOfFile: path, usedEncoding: nil)
self = ns._swiftObject
}
// - (instancetype)
// initWithContentsOfURL:(NSURL *)url
// encoding:(NSStringEncoding)enc
// error:(NSError**)error
/// Produces a string created by reading data from a given URL
/// interpreted using a given encoding. Errors are written into the
/// inout `error` argument.
public init(
contentsOf url: URL,
encoding enc: Encoding
) throws {
let ns = try NSString(contentsOf: url, encoding: enc.rawValue)
self = ns._swiftObject
}
// - (instancetype)
// initWithContentsOfURL:(NSURL *)url
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
/// Produces a string created by reading data from a given URL
/// and returns by reference the encoding used to interpret the
/// data. Errors are written into the inout `error` argument.
public init(
contentsOf url: URL,
usedEncoding: inout Encoding
) throws {
var enc: UInt = 0
let ns = try NSString(contentsOf: url as URL, usedEncoding: &enc)
usedEncoding = Encoding(rawValue: enc)
self = ns._swiftObject
}
public init(
contentsOf url: URL
) throws {
let ns = try NSString(contentsOf: url, usedEncoding: nil)
self = ns._swiftObject
}
// - (instancetype)
// initWithCString:(const char *)nullTerminatedCString
// encoding:(NSStringEncoding)encoding
/// Produces a string containing the bytes in a given C array,
/// interpreted according to a given encoding.
public init?(
cString: UnsafePointer<CChar>,
encoding enc: Encoding
) {
if let ns = NSString(CString: cString, encoding: enc.rawValue) {
self = ns._swiftObject
} else {
return nil
}
}
// FIXME: handle optional locale with default arguments
// - (instancetype)
// initWithData:(NSData *)data
// encoding:(NSStringEncoding)encoding
/// Returns a `String` initialized by converting given `data` into
/// Unicode characters using a given `encoding`.
public init?(data: Data, encoding: Encoding) {
guard let s = NSString(data: data, encoding: encoding.rawValue) else { return nil }
self = s._swiftObject
}
// - (instancetype)initWithFormat:(NSString *)format, ...
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted.
public init(format: String, _ arguments: CVarArg...) {
self = String(format: format, arguments: arguments)
}
// - (instancetype)
// initWithFormat:(NSString *)format
// arguments:(va_list)argList
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to the user's default locale.
public init(format: String, arguments: [CVarArg]) {
self = String(format: format, locale: nil, arguments: arguments)
}
// - (instancetype)initWithFormat:(NSString *)format locale:(id)locale, ...
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to given locale information.
public init(format: String, locale: Locale?, _ args: CVarArg...) {
self = String(format: format, locale: locale, arguments: args)
}
// - (instancetype)
// initWithFormat:(NSString *)format
// locale:(id)locale
// arguments:(va_list)argList
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to given locale information.
public init(format: String, locale: Locale?, arguments: [CVarArg]) {
_precondition(
_countFormatSpecifiers(format) <= arguments.count,
"Too many format specifiers (%<letter>) provided for the argument list"
)
self = withVaList(arguments) {
NSString(format: format, locale: locale, arguments: $0)._swiftObject
}
}
//===--- Already provided by core Swift ---------------------------------===//
// - (instancetype)initWithString:(NSString *)aString
//===--- Initializers that can fail dropped for factory functions -------===//
// - (instancetype)initWithUTF8String:(const char *)bytes
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property NSInteger integerValue;
// @property Int intValue;
//===--- Omitted by apparent agreement during API review 5/20/2014 ------===//
// @property BOOL absolutePath;
// - (BOOL)isEqualToString:(NSString *)aString
//===--- Kept for consistency with API review results 5/20/2014 ---------===//
// We decided to keep pathWithComponents, so keeping this too
// @property NSString lastPathComponent;
/// Returns the last path component of the `String`.
@available(*, unavailable, message: "Use lastPathComponent on URL instead.")
public var lastPathComponent: String {
return _ns.lastPathComponent
}
//===--- Renamed by agreement during API review 5/20/2014 ---------------===//
// @property NSUInteger length;
/// Returns the number of Unicode characters in the `String`.
@available(*, unavailable,
message: "Take the count of a UTF-16 view instead, i.e. str.utf16.count")
public var utf16Count: Int {
return _ns.length
}
// - (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc
/// Returns the number of bytes required to store the
/// `String` in a given encoding.
public func lengthOfBytes(using encoding: Encoding) -> Int {
return _ns.lengthOfBytes(using: encoding.rawValue)
}
// - (NSRange)lineRangeForRange:(NSRange)aRange
/// Returns the range of characters representing the line or lines
/// containing a given range.
public func lineRange(for aRange: Range<Index>) -> Range<Index> {
return _range(_ns.lineRange(for: _toNSRange(aRange)))
}
// - (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)aString
/// Compares the string and a given string using a
/// case-insensitive, localized, comparison.
public
func localizedCaseInsensitiveCompare(_ aString: String) -> ComparisonResult {
return _ns.localizedCaseInsensitiveCompare(aString)
}
// - (NSComparisonResult)localizedCompare:(NSString *)aString
/// Compares the string and a given string using a localized
/// comparison.
public func localizedCompare(_ aString: String) -> ComparisonResult {
return _ns.localizedCompare(aString)
}
/// Compares strings as sorted by the Finder.
public func localizedStandardCompare(_ string: String) -> ComparisonResult {
return _ns.localizedStandardCompare(string)
}
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property long long longLongValue
// @property (readonly, copy) NSString *localizedLowercase NS_AVAILABLE(10_11, 9_0);
/// A lowercase version of the string that is produced using the current
/// locale.
public var localizedLowercase: String {
return _ns.localizedLowercase
}
// - (NSString *)lowercaseStringWithLocale:(Locale *)locale
/// Returns a version of the string with all letters
/// converted to lowercase, taking into account the specified
/// locale.
public func lowercased(with locale: Locale?) -> String {
return _ns.lowercased(with: locale)
}
// - (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc
/// Returns the maximum number of bytes needed to store the
/// `String` in a given encoding.
public
func maximumLengthOfBytes(using encoding: Encoding) -> Int {
return _ns.maximumLengthOfBytes(using: encoding.rawValue)
}
// - (NSRange)paragraphRangeForRange:(NSRange)aRange
/// Returns the range of characters representing the
/// paragraph or paragraphs containing a given range.
public func paragraphRange(for aRange: Range<Index>) -> Range<Index> {
return _range(_ns.paragraphRange(for: _toNSRange(aRange)))
}
// @property NSArray* pathComponents
/// Returns an array of NSString objects containing, in
/// order, each path component of the `String`.
@available(*, unavailable, message: "Use pathComponents on URL instead.")
public var pathComponents: [String] {
return _ns.pathComponents
}
// @property NSString* pathExtension;
/// Interprets the `String` as a path and returns the
/// `String`'s extension, if any.
@available(*, unavailable, message: "Use pathExtension on URL instead.")
public var pathExtension: String {
return _ns.pathExtension
}
// @property NSString* precomposedStringWithCanonicalMapping;
/// Returns a string made by normalizing the `String`'s
/// contents using Form C.
public var precomposedStringWithCanonicalMapping: String {
return _ns.precomposedStringWithCanonicalMapping
}
// @property NSString * precomposedStringWithCompatibilityMapping;
/// Returns a string made by normalizing the `String`'s