-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathString.swift
2421 lines (2100 loc) · 69.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
// RUN: %empty-directory(%t)
// RUN: %target-clang -fobjc-arc %S/Inputs/NSSlowString/NSSlowString.m -c -o %t/NSSlowString.o
// RUN: %target-build-swift -I %S/Inputs/NSSlowString/ %t/NSSlowString.o %s -Xfrontend -disable-access-control -o %t/String
// RUN: %target-codesign %t/String
// RUN: %target-run %t/String
// REQUIRES: executable_test
// XFAIL: interpret
// UNSUPPORTED: freestanding
// Only run these tests with a just-built stdlib.
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime
// With a non-optimized stdlib the test takes very long.
// REQUIRES: optimized_stdlib
import StdlibUnittest
import StdlibCollectionUnittest
#if _runtime(_ObjC)
import NSSlowString
import Foundation // For NSRange
#endif
#if os(Windows)
import ucrt
#endif
extension Collection {
internal func index(_nth n: Int) -> Index {
precondition(n >= 0)
return index(startIndex, offsetBy: n)
}
internal func index(_nthLast n: Int) -> Index {
precondition(n >= 0)
return index(endIndex, offsetBy: -n)
}
}
extension String {
var nativeCapacity: Int {
switch self._classify()._form {
case ._native: break
default: preconditionFailure()
}
return self._classify()._capacity
}
var capacity: Int {
return self._classify()._capacity
}
var unusedCapacity: Int {
return Swift.max(0, self._classify()._capacity - self._classify()._count)
}
var bufferID: ObjectIdentifier? {
return _rawIdentifier()
}
func _rawIdentifier() -> ObjectIdentifier? {
return self._classify()._objectIdentifier
}
var byteWidth: Int {
return _classify()._isASCII ? 1 : 2
}
}
extension Substring {
var bufferID: ObjectIdentifier? {
return base.bufferID
}
}
// A thin wrapper around _StringGuts implementing RangeReplaceableCollection
struct StringFauxUTF16Collection: RangeReplaceableCollection, RandomAccessCollection {
typealias Element = UTF16.CodeUnit
typealias Index = Int
typealias Indices = CountableRange<Int>
init(_ guts: _StringGuts) {
self._str = String(guts)
}
init() {
self.init(_StringGuts())
}
var _str: String
var _guts: _StringGuts { return _str._guts }
var startIndex: Index { return 0 }
var endIndex: Index { return _str.utf16.count }
var indices: Indices { return startIndex..<endIndex }
subscript(position: Index) -> Element {
return _str.utf16[_str._toUTF16Index(position)]
}
mutating func replaceSubrange<C>(
_ subrange: Range<Index>,
with newElements: C
) where C : Collection, C.Element == Element {
var utf16 = Array(_str.utf16)
utf16.replaceSubrange(subrange, with: newElements)
self._str = String(decoding: utf16, as: UTF16.self)
}
mutating func reserveCapacity(_ n: Int) {
_str.reserveCapacity(n)
}
}
var StringTests = TestSuite("StringTests")
StringTests.test("sizeof") {
#if _pointerBitWidth(_32)
expectEqual(12, MemoryLayout<String>.size)
#else
expectEqual(16, MemoryLayout<String>.size)
#endif
}
StringTests.test("AssociatedTypes-UTF8View") {
typealias View = String.UTF8View
expectCollectionAssociatedTypes(
collectionType: View.self,
iteratorType: View.Iterator.self,
subSequenceType: Substring.UTF8View.self,
indexType: View.Index.self,
indicesType: DefaultIndices<View>.self)
}
StringTests.test("AssociatedTypes-UTF16View") {
typealias View = String.UTF16View
expectCollectionAssociatedTypes(
collectionType: View.self,
iteratorType: View.Iterator.self,
subSequenceType: Substring.UTF16View.self,
indexType: View.Index.self,
indicesType: View.Indices.self)
}
StringTests.test("AssociatedTypes-UnicodeScalarView") {
typealias View = String.UnicodeScalarView
expectCollectionAssociatedTypes(
collectionType: View.self,
iteratorType: View.Iterator.self,
subSequenceType: Substring.UnicodeScalarView.self,
indexType: View.Index.self,
indicesType: DefaultIndices<View>.self)
}
StringTests.test("AssociatedTypes-CharacterView") {
expectCollectionAssociatedTypes(
collectionType: String.self,
iteratorType: String.Iterator.self,
subSequenceType: Substring.self,
indexType: String.Index.self,
indicesType: DefaultIndices<String>.self)
}
func checkUnicodeScalarViewIteration(
_ expectedScalars: [UInt32], _ str: String
) {
do {
let us = str.unicodeScalars
var i = us.startIndex
let end = us.endIndex
var decoded: [UInt32] = []
while i != end {
expectTrue(i < us.index(after: i)) // Check for Comparable conformance
decoded.append(us[i].value)
i = us.index(after: i)
}
expectEqual(expectedScalars, decoded)
}
do {
let us = str.unicodeScalars
let start = us.startIndex
var i = us.endIndex
var decoded: [UInt32] = []
while i != start {
i = us.index(before: i)
decoded.append(us[i].value)
}
expectEqual(expectedScalars, decoded)
}
}
StringTests.test("unicodeScalars") {
checkUnicodeScalarViewIteration([], "")
checkUnicodeScalarViewIteration([ 0x0000 ], "\u{0000}")
checkUnicodeScalarViewIteration([ 0x0041 ], "A")
checkUnicodeScalarViewIteration([ 0x007f ], "\u{007f}")
checkUnicodeScalarViewIteration([ 0x0080 ], "\u{0080}")
checkUnicodeScalarViewIteration([ 0x07ff ], "\u{07ff}")
checkUnicodeScalarViewIteration([ 0x0800 ], "\u{0800}")
checkUnicodeScalarViewIteration([ 0xd7ff ], "\u{d7ff}")
checkUnicodeScalarViewIteration([ 0x8000 ], "\u{8000}")
checkUnicodeScalarViewIteration([ 0xe000 ], "\u{e000}")
checkUnicodeScalarViewIteration([ 0xfffd ], "\u{fffd}")
checkUnicodeScalarViewIteration([ 0xffff ], "\u{ffff}")
checkUnicodeScalarViewIteration([ 0x10000 ], "\u{00010000}")
checkUnicodeScalarViewIteration([ 0x10ffff ], "\u{0010ffff}")
}
StringTests.test("Index/Comparable") {
let empty = ""
expectTrue(empty.startIndex == empty.endIndex)
expectFalse(empty.startIndex != empty.endIndex)
expectTrue(empty.startIndex <= empty.endIndex)
expectTrue(empty.startIndex >= empty.endIndex)
expectFalse(empty.startIndex > empty.endIndex)
expectFalse(empty.startIndex < empty.endIndex)
let nonEmpty = "borkus biqualificated"
expectFalse(nonEmpty.startIndex == nonEmpty.endIndex)
expectTrue(nonEmpty.startIndex != nonEmpty.endIndex)
expectTrue(nonEmpty.startIndex <= nonEmpty.endIndex)
expectFalse(nonEmpty.startIndex >= nonEmpty.endIndex)
expectFalse(nonEmpty.startIndex > nonEmpty.endIndex)
expectTrue(nonEmpty.startIndex < nonEmpty.endIndex)
}
StringTests.test("Index/Hashable") {
let s = "abcdef"
let t = Set(s.indices)
expectEqual(s.count, t.count)
expectTrue(t.contains(s.startIndex))
}
StringTests.test("ForeignIndexes/Valid") {
// It is actually unclear what the correct behavior is. This test is just a
// change detector.
//
// <rdar://problem/18037897> Design, document, implement invalidation model
// for foreign String indexes
do {
let donor = "abcdef"
let acceptor = "uvwxyz"
expectEqual("u", acceptor[donor.startIndex])
expectEqual("wxy",
acceptor[donor.index(_nth: 2)..<donor.index(_nth: 5)])
}
do {
let donor = "abcdef"
let acceptor = "\u{1f601}\u{1f602}\u{1f603}"
expectEqual("\u{1f601}", acceptor[donor.startIndex])
// Scalar alignment fixes and checks were added in 5.1, so we don't get the
// expected behavior on prior runtimes.
guard _hasSwift_5_1() else { return }
// Donor's second index is scalar-aligned in donor, but not acceptor. This
// will trigger a stdlib assertion.
let donorSecondIndex = donor.index(after: donor.startIndex)
if _isStdlibInternalChecksEnabled() {
expectCrash { _ = acceptor[donorSecondIndex] }
} else {
expectEqual(1, acceptor[donorSecondIndex].utf8.count)
expectEqual(0x9F, acceptor[donorSecondIndex].utf8.first!)
}
}
}
StringTests.test("ForeignIndexes/UnexpectedCrash") {
let donor = "\u{1f601}\u{1f602}\u{1f603}"
let acceptor = "abcdef"
// Adjust donor.startIndex to ensure it caches a stride
let start = donor.index(before: donor.index(after: donor.startIndex))
// Grapheme stride cache under noop scalar alignment was fixed in 5.1, so we
// get a different answer prior.
guard _hasSwift_5_1() else { return }
// `start` has a cached stride greater than 1, so subscript will trigger an
// assertion when it makes a multi-grapheme-cluster Character.
if _isStdlibInternalChecksEnabled() {
expectCrash { _ = acceptor[start] }
} else {
expectEqual("abcd", String(acceptor[start]))
}
}
StringTests.test("ForeignIndexes/subscript(Index)/OutOfBoundsTrap") {
let donor = "abcdef"
let acceptor = "uvw"
expectEqual("u", acceptor[donor.index(_nth: 0)])
expectEqual("v", acceptor[donor.index(_nth: 1)])
expectEqual("w", acceptor[donor.index(_nth: 2)])
let i = donor.index(_nth: 3)
expectCrashLater()
_ = acceptor[i]
}
StringTests.test("String/subscript(_:Range)") {
let s = "foobar"
let from = s.startIndex
let to = s.index(before: s.endIndex)
let actual = s[from..<to]
expectEqual("fooba", actual)
}
StringTests.test("String/subscript(_:ClosedRange)") {
let s = "foobar"
let from = s.startIndex
let to = s.index(before: s.endIndex)
let actual = s[from...to]
expectEqual(s, actual)
}
StringTests.test("ForeignIndexes/subscript(Range)/OutOfBoundsTrap/1") {
let donor = "abcdef"
let acceptor = "uvw"
expectEqual("uvw", acceptor[donor.startIndex..<donor.index(_nth: 3)])
let r = donor.startIndex..<donor.index(_nth: 4)
expectCrashLater()
_ = acceptor[r]
}
StringTests.test("ForeignIndexes/subscript(Range)/OutOfBoundsTrap/2") {
let donor = "abcdef"
let acceptor = "uvw"
expectEqual("uvw", acceptor[donor.startIndex..<donor.index(_nth: 3)])
let r = donor.index(_nth: 4)..<donor.index(_nth: 5)
expectCrashLater()
_ = acceptor[r]
}
StringTests.test("ForeignIndexes/subscript(ClosedRange)/OutOfBoundsTrap/1") {
let donor = "abcdef"
let acceptor = "uvw"
expectEqual("uvw", acceptor[donor.startIndex...donor.index(_nth: 2)])
let r = donor.startIndex...donor.index(_nth: 3)
expectCrashLater()
_ = acceptor[r]
}
StringTests.test("ForeignIndexes/subscript(ClosedRange)/OutOfBoundsTrap/2") {
let donor = "abcdef"
let acceptor = "uvw"
expectEqual("uvw", acceptor[donor.startIndex...donor.index(_nth: 2)])
let r = donor.index(_nth: 3)...donor.index(_nth: 5)
expectCrashLater()
_ = acceptor[r]
}
StringTests.test("ForeignIndexes/replaceSubrange/OutOfBoundsTrap/1") {
let donor = "abcdef"
var acceptor = "uvw"
acceptor.replaceSubrange(
donor.startIndex..<donor.index(_nth: 1), with: "u")
expectEqual("uvw", acceptor)
let r = donor.startIndex..<donor.index(_nth: 4)
expectCrashLater()
acceptor.replaceSubrange(r, with: "")
}
StringTests.test("ForeignIndexes/replaceSubrange/OutOfBoundsTrap/2") {
let donor = "abcdef"
var acceptor = "uvw"
acceptor.replaceSubrange(
donor.startIndex..<donor.index(_nth: 1), with: "u")
expectEqual("uvw", acceptor)
let r = donor.index(_nth: 4)..<donor.index(_nth: 5)
expectCrashLater()
acceptor.replaceSubrange(r, with: "")
}
StringTests.test("ForeignIndexes/removeAt/OutOfBoundsTrap") {
do {
let donor = "abcdef"
var acceptor = "uvw"
let removed = acceptor.remove(at: donor.startIndex)
expectEqual("u", removed)
expectEqual("vw", acceptor)
}
let donor = "abcdef"
var acceptor = "uvw"
let i = donor.index(_nth: 4)
expectCrashLater()
acceptor.remove(at: i)
}
StringTests.test("ForeignIndexes/removeSubrange/OutOfBoundsTrap/1") {
do {
let donor = "abcdef"
var acceptor = "uvw"
acceptor.removeSubrange(
donor.startIndex..<donor.index(after: donor.startIndex))
expectEqual("vw", acceptor)
}
let donor = "abcdef"
var acceptor = "uvw"
let r = donor.startIndex..<donor.index(_nth: 4)
expectCrashLater()
acceptor.removeSubrange(r)
}
StringTests.test("ForeignIndexes/removeSubrange/OutOfBoundsTrap/2") {
let donor = "abcdef"
var acceptor = "uvw"
let r = donor.index(_nth: 4)..<donor.index(_nth: 5)
expectCrashLater()
acceptor.removeSubrange(r)
}
StringTests.test("hasPrefix")
.skip(.nativeRuntime("String.hasPrefix undefined without _runtime(_ObjC)"))
.code {
#if _runtime(_ObjC)
expectTrue("".hasPrefix(""))
expectFalse("".hasPrefix("a"))
expectTrue("a".hasPrefix(""))
expectTrue("a".hasPrefix("a"))
// U+0301 COMBINING ACUTE ACCENT
// U+00E1 LATIN SMALL LETTER A WITH ACUTE
expectFalse("abc".hasPrefix("a\u{0301}"))
expectFalse("a\u{0301}bc".hasPrefix("a"))
expectTrue("\u{00e1}bc".hasPrefix("a\u{0301}"))
expectTrue("a\u{0301}bc".hasPrefix("\u{00e1}"))
#else
expectUnreachable()
#endif
}
StringTests.test("literalConcatenation") {
do {
// UnicodeScalarLiteral + UnicodeScalarLiteral
var s = "1" + "2"
expectType(String.self, &s)
expectEqual("12", s)
}
do {
// UnicodeScalarLiteral + ExtendedGraphemeClusterLiteral
var s = "1" + "a\u{0301}"
expectType(String.self, &s)
expectEqual("1a\u{0301}", s)
}
do {
// UnicodeScalarLiteral + StringLiteral
var s = "1" + "xyz"
expectType(String.self, &s)
expectEqual("1xyz", s)
}
do {
// ExtendedGraphemeClusterLiteral + UnicodeScalar
var s = "a\u{0301}" + "z"
expectType(String.self, &s)
expectEqual("a\u{0301}z", s)
}
do {
// ExtendedGraphemeClusterLiteral + ExtendedGraphemeClusterLiteral
var s = "a\u{0301}" + "e\u{0302}"
expectType(String.self, &s)
expectEqual("a\u{0301}e\u{0302}", s)
}
do {
// ExtendedGraphemeClusterLiteral + StringLiteral
var s = "a\u{0301}" + "xyz"
expectType(String.self, &s)
expectEqual("a\u{0301}xyz", s)
}
do {
// StringLiteral + UnicodeScalar
var s = "xyz" + "1"
expectType(String.self, &s)
expectEqual("xyz1", s)
}
do {
// StringLiteral + ExtendedGraphemeClusterLiteral
var s = "xyz" + "a\u{0301}"
expectType(String.self, &s)
expectEqual("xyza\u{0301}", s)
}
do {
// StringLiteral + StringLiteral
var s = "xyz" + "abc"
expectType(String.self, &s)
expectEqual("xyzabc", s)
}
}
StringTests.test("substringDoesNotCopy/Swift3")
.xfail(.always("Swift 3 compatibility: Self-sliced Strings are copied"))
.code {
let size = 16
for sliceStart in [0, 2, 8, size] {
for sliceEnd in [0, 2, 8, sliceStart + 1] {
if sliceStart > size || sliceEnd > size || sliceEnd < sliceStart {
continue
}
var s0 = String(repeating: "x", count: size)
let originalIdentity = s0.bufferID
s0 = String(s0[s0.index(_nth: sliceStart)..<s0.index(_nth: sliceEnd)])
expectEqual(originalIdentity, s0.bufferID)
}
}
}
StringTests.test("substringDoesNotCopy/Swift4") {
let size = 16
for sliceStart in [0, 2, 8, size] {
for sliceEnd in [0, 2, 8, sliceStart + 1] {
if sliceStart > size || sliceEnd > size || sliceEnd < sliceStart {
continue
}
let s0 = String(repeating: "x", count: size)
let originalIdentity = s0.bufferID
let s1 = s0[s0.index(_nth: sliceStart)..<s0.index(_nth: sliceEnd)]
expectEqual(s1.bufferID, originalIdentity)
}
}
}
StringTests.test("appendToEmptyString") {
let x = "Bumfuzzle"
expectNil(x.bufferID)
// Appending to empty string literal should replace it.
var a1 = ""
a1 += x
expectNil(a1.bufferID)
// Appending to native string should keep the existing buffer.
var b1 = ""
b1.reserveCapacity(20)
let b1ID = b1.bufferID
b1 += x
expectEqual(b1.bufferID, b1ID)
// .append(_:) should have the same behavior as +=
var a2 = ""
a2.append(x)
expectNil(a2.bufferID)
var b2 = ""
b2.reserveCapacity(20)
let b2ID = b2.bufferID
b2.append(x)
expectEqual(b2.bufferID, b2ID)
}
StringTests.test("Swift3Slice/Empty") {
let size = 16
let s = String(repeating: "x", count: size)
expectNotNil(s.bufferID)
for i in 0 ... size {
let slice = s[s.index(_nth: i)..<s.index(_nth: i)]
// Empty substrings still have indices relative to their base and can refer
// to the whole string. If the whole string has storage, so should its
// substring.
expectNotNil(slice.bufferID)
}
}
StringTests.test("Swift3Slice/Full") {
let size = 16
let s = String(repeating: "x", count: size)
let slice = s[s.startIndex..<s.endIndex]
// Most Swift 3 substrings are extracted into their own buffer,
// but if the substring covers the full original string, it is used instead.
expectEqual(slice.bufferID, s.bufferID)
}
StringTests.test("appendToSubstring") {
for initialSize in 1..<16 {
for sliceStart in [0, 2, 8, initialSize] {
for sliceEnd in [0, 2, 8, sliceStart + 1] {
if sliceStart > initialSize || sliceEnd > initialSize ||
sliceEnd < sliceStart {
continue
}
var s0 = String(repeating: "x", count: initialSize)
s0 = String(s0[s0.index(_nth: sliceStart)..<s0.index(_nth: sliceEnd)])
s0 += "x"
expectEqual(
String(
repeating: "x",
count: sliceEnd - sliceStart + 1),
s0)
}
}
}
}
StringTests.test("appendToSubstringBug")
.xfail(.always("Swift 3 compatibility: Self-sliced Strings are copied"))
.code {
// String used to have a heap overflow bug when one attempted to append to a
// substring that pointed to the end of a string buffer.
//
// Unused capacity
// VVV
// String buffer [abcdefghijk ]
// ^ ^
// +----+
// Substring -----------+
//
// In the example above, there are only three elements of unused capacity.
// The bug was that the implementation mistakenly assumed 9 elements of
// unused capacity (length of the prefix "abcdef" plus truly unused elements
// at the end).
func stringWithUnusedCapacity() -> (String, Int) {
var s0 = String(repeating: "x", count: 17)
if s0.unusedCapacity == 0 { s0 += "y" }
let cap = s0.unusedCapacity
expectNotEqual(0, cap)
// This sorta checks for the original bug
expectEqual(
cap, String(s0[s0.index(_nth: 1)..<s0.endIndex]).unusedCapacity)
return (s0, cap)
}
do {
var (s, _) = { ()->(String, Int) in
let (s0, unused) = stringWithUnusedCapacity()
return (String(s0[s0.index(_nth: 5)..<s0.endIndex]), unused)
}()
let originalID = s.bufferID
// Appending to a String always results in storage that
// starts at the beginning of its native buffer
s += "z"
expectNotEqual(originalID, s.bufferID)
}
do {
var (s, _) = { ()->(Substring, Int) in
let (s0, unused) = stringWithUnusedCapacity()
return (s0[s0.index(_nth: 5)..<s0.endIndex], unused)
}()
let originalID = s.bufferID
// FIXME: Ideally, appending to a Substring with a unique buffer reference
// does not reallocate unless necessary. Today, however, it appears to do
// so unconditionally unless the slice falls at the beginning of its buffer.
s += "z"
expectNotEqual(originalID, s.bufferID)
}
// Try again at the beginning of the buffer
do {
var (s, unused) = { ()->(Substring, Int) in
let (s0, unused) = stringWithUnusedCapacity()
return (s0[...], unused)
}()
let originalID = s.bufferID
s += "z"
expectEqual(originalID, s.bufferID)
s += String(repeating: "z", count: unused - 1)
expectEqual(originalID, s.bufferID)
s += "."
expectNotEqual(originalID, s.bufferID)
unused += 0 // warning suppression
}
}
StringTests.test("COW/removeSubrange/start") {
var str = "12345678"
str.reserveCapacity(1024) // Ensure on heap
let literalIdentity = str.bufferID
// Check literal-to-heap reallocation.
do {
let slice = str
expectNotNil(literalIdentity)
expectEqual(literalIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
expectEqual("12345678", str)
expectEqual("12345678", slice)
// This mutation should reallocate the string.
str.removeSubrange(str.startIndex..<str.index(_nth: 1))
expectNotEqual(literalIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
let heapStrIdentity = str.bufferID
expectEqual("2345678", str)
expectEqual("12345678", slice)
// No more reallocations are expected.
str.removeSubrange(str.startIndex..<str.index(_nth: 1))
expectEqual(heapStrIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
expectEqual("345678", str)
expectEqual("12345678", slice)
}
// Check heap-to-heap reallocation.
expectEqual("345678", str)
do {
str.reserveCapacity(1024) // Ensure on heap
let heapStrIdentity1 = str.bufferID
let slice = str
expectNotNil(heapStrIdentity1)
expectEqual(heapStrIdentity1, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
expectEqual("345678", str)
expectEqual("345678", slice)
// This mutation should reallocate the string.
str.removeSubrange(str.startIndex..<str.index(_nth: 1))
expectNotEqual(heapStrIdentity1, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
let heapStrIdentity2 = str.bufferID
expectEqual("45678", str)
expectEqual("345678", slice)
// No more reallocations are expected.
str.removeSubrange(str.startIndex..<str.index(_nth: 1))
expectEqual(heapStrIdentity2, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
expectEqual("5678", str)
expectEqual("345678", slice)
}
}
StringTests.test("COW/removeSubrange/end") {
var str = "12345678"
str.reserveCapacity(1024) // Ensure on heap
let literalIdentity = str.bufferID
// Check literal-to-heap reallocation.
expectEqual("12345678", str)
do {
let slice = str
expectNotNil(literalIdentity)
expectEqual(literalIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
expectEqual("12345678", str)
expectEqual("12345678", slice)
// This mutation should reallocate the string.
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
expectNotEqual(literalIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
let heapStrIdentity = str.bufferID
expectEqual("1234567", str)
expectEqual("12345678", slice)
// No more reallocations are expected.
str.append("x")
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
expectEqual(heapStrIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
expectEqual("1234567", str)
expectEqual("12345678", slice)
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
str.append("x")
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
expectEqual(heapStrIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
expectEqual("123456", str)
expectEqual("12345678", slice)
}
// Check heap-to-heap reallocation.
expectEqual("123456", str)
do {
str.reserveCapacity(1024) // Ensure on heap
let heapStrIdentity1 = str.bufferID
let slice = str
expectNotNil(heapStrIdentity1)
expectEqual(heapStrIdentity1, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
expectEqual("123456", str)
expectEqual("123456", slice)
// This mutation should reallocate the string.
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
expectNotEqual(heapStrIdentity1, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
let heapStrIdentity = str.bufferID
expectEqual("12345", str)
expectEqual("123456", slice)
// No more reallocations are expected.
str.append("x")
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
expectEqual(heapStrIdentity, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
expectEqual("12345", str)
expectEqual("123456", slice)
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
str.append("x")
str.removeSubrange(str.index(_nthLast: 1)..<str.endIndex)
expectEqual(heapStrIdentity, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
expectEqual("1234", str)
expectEqual("123456", slice)
}
}
StringTests.test("COW/replaceSubrange/end") {
// Check literal-to-heap reallocation.
do {
var str = "12345678"
str.reserveCapacity(1024) // Ensure on heap
let literalIdentity = str.bufferID
var slice = str[str.startIndex..<str.index(_nth: 7)]
expectNotNil(literalIdentity)
expectEqual(literalIdentity, str.bufferID)
expectEqual(literalIdentity, slice.bufferID)
expectEqual("12345678", str)
expectEqual("1234567", slice)
// This mutation should reallocate the string.
slice.replaceSubrange(slice.endIndex..<slice.endIndex, with: "a")
expectNotEqual(literalIdentity, slice.bufferID)
expectEqual(literalIdentity, str.bufferID)
let heapStrIdentity = slice.bufferID
expectEqual("1234567a", slice)
expectEqual("12345678", str)
// No more reallocations are expected.
slice.replaceSubrange(
slice.index(_nthLast: 1)..<slice.endIndex, with: "b")
expectEqual(heapStrIdentity, slice.bufferID)
expectEqual(literalIdentity, str.bufferID)
expectEqual("1234567b", slice)
expectEqual("12345678", str)
}
// Check literal-to-heap reallocation.
do {
var str = "12345678"
let literalIdentity = str.bufferID
// Move the string to the heap.
str.reserveCapacity(32)
expectNotEqual(literalIdentity, str.bufferID)
let heapStrIdentity1 = str.bufferID
expectNotNil(heapStrIdentity1)
// FIXME: We have to use Swift 4's Substring to get the desired storage
// semantics; in Swift 3 mode, self-sliced strings get allocated a new
// buffer immediately.
var slice = str[str.startIndex..<str.index(_nth: 7)]
expectEqual(heapStrIdentity1, str.bufferID)
expectEqual(heapStrIdentity1, slice.bufferID)
// This mutation should reallocate the string.
slice.replaceSubrange(slice.endIndex..<slice.endIndex, with: "a")
expectNotEqual(heapStrIdentity1, slice.bufferID)
expectEqual(heapStrIdentity1, str.bufferID)
let heapStrIdentity2 = slice.bufferID
expectEqual("1234567a", slice)
expectEqual("12345678", str)
// No more reallocations are expected.
slice.replaceSubrange(
slice.index(_nthLast: 1)..<slice.endIndex, with: "b")
expectEqual(heapStrIdentity2, slice.bufferID)
expectEqual(heapStrIdentity1, str.bufferID)
expectEqual("1234567b", slice)
expectEqual("12345678", str)
}
}
func asciiString<
S: Sequence
>(_ content: S) -> String
where S.Iterator.Element == Character {
var s = String()
s.append(contentsOf: content)
expectTrue(s._classify()._isASCII)
return s
}
StringTests.test("stringGutsExtensibility")
.skip(.nativeRuntime("Foundation dependency"))
.code {
#if _runtime(_ObjC)
let ascii = UTF16.CodeUnit(UnicodeScalar("X").value)
let nonAscii = UTF16.CodeUnit(UnicodeScalar("é").value)
for k in 0..<3 {
for count in 1..<16 {
for boundary in 0..<count {
var x = (
k == 0 ? asciiString("b")
: k == 1 ? ("b" as NSString as String)
: ("b" as NSMutableString as String)
)
if k == 0 { expectTrue(x._guts.isFastUTF8) }
for i in 0..<count {
x.append(String(
decoding: repeatElement(i < boundary ? ascii : nonAscii, count: 3),
as: UTF16.self))
}
// Make sure we can append pure ASCII to wide storage
x.append(String(
decoding: repeatElement(ascii, count: 2), as: UTF16.self))
expectEqualSequence(
[UTF16.CodeUnit(UnicodeScalar("b").value)]
+ Array(repeatElement(ascii, count: 3*boundary))
+ repeatElement(nonAscii, count: 3*(count - boundary))
+ repeatElement(ascii, count: 2),
StringFauxUTF16Collection(x.utf16)
)
}
}
}
#else
expectUnreachable()
#endif
}
StringTests.test("stringGutsReserve")
.skip(.nativeRuntime("Foundation dependency"))
.code {
#if _runtime(_ObjC)
guard #available(macOS 10.13, iOS 11.0, tvOS 11.0, *) else { return }
for k in 0...7 {
var base: String
var startedNative: Bool
let shared: String = "X"
// Managed native, unmanaged native, or small
func isSwiftNative(_ s: String) -> Bool {
switch s._classify()._form {
case ._native: return true
case ._small: return true
case ._immortal: return true
default: return false
}
}
switch k {
case 0: (base, startedNative) = (String(), true)
case 1: (base, startedNative) = (asciiString("x"), true)
case 2: (base, startedNative) = ("Ξ", true)
#if _pointerBitWidth(_32)
case 3: (base, startedNative) = ("x" as NSString as String, false)
case 4: (base, startedNative) = ("x" as NSMutableString as String, false)
#else
case 3: (base, startedNative) = ("x" as NSString as String, true)
case 4: (base, startedNative) = ("x" as NSMutableString as String, true)
#endif
case 5: (base, startedNative) = (shared, true)
case 6: (base, startedNative) = ("xá" as NSString as String, false)
case 7: (base, startedNative) = ("xá" as NSMutableString as String, false)
default:
fatalError("case unhandled!")
}
// TODO: rdar://112643333
//expectEqual(isSwiftNative(base), startedNative)
let originalBuffer = base.bufferID
let isUnique = base._guts.isUniqueNative
let startedUnique =
startedNative &&
base._classify()._objectIdentifier != nil &&
isUnique
base.reserveCapacity(16)
// Now it's unique
// If it was already native and unique, no reallocation
if startedUnique && startedNative {
expectEqual(originalBuffer, base.bufferID)
}