Skip to content

Commit 60cfb65

Browse files
authored
Merge pull request #27477 from Catfish-Man/swift-5.1-branch
[5.1] Fix sub-scalar index distances in foreign UTF8 views
2 parents 25a507d + 49c8cca commit 60cfb65

File tree

5 files changed

+6
-4
lines changed

5 files changed

+6
-4
lines changed

stdlib/public/core/StringBridge.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ internal func _cocoaStringUTF8Count(
9595
_ target: _CocoaString,
9696
range: Range<Int>
9797
) -> Int? {
98+
if range.isEmpty { return 0 }
9899
var count = 0
99100
let len = _stdlib_binary_CFStringGetLength(target)
100101
let converted = _swift_stdlib_CFStringGetBytes(

stdlib/public/core/StringUTF8View.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -505,7 +505,7 @@ extension String.UTF8View {
505505
// _cocoaStringUTF8Count gave us the scalar aligned count, but we still
506506
// need to compensate for sub-scalar indexing, e.g. if `i` is in the
507507
// middle of a two-byte UTF8 scalar.
508-
let refinedCount = count - (i.transcodedOffset + j.transcodedOffset)
508+
let refinedCount = (count - i.transcodedOffset) + j.transcodedOffset
509509
_internalInvariant(refinedCount == _distance(from: i, to: j))
510510
return refinedCount
511511
}

test/stdlib/Inputs/FoundationBridge/FoundationBridge.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,12 +86,12 @@ static inline BOOL NSStringBridgeTestEqual(NSString * _Nonnull a, NSString * _No
8686
}
8787

8888
static inline NSString *getNSStringWithUnpairedSurrogate() {
89-
unichar chars[16] = {
89+
unichar chars[19] = {
9090
0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020,
9191
0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020,
9292
0x0020, 0x0020, 0x0020, 0x0020, 0x0020, 0x0020,
9393
0xD800 };
94-
return [NSString stringWithCharacters:chars length:1];
94+
return [NSString stringWithCharacters:chars length:19];
9595
}
9696

9797
NS_ASSUME_NONNULL_END

test/stdlib/Inputs/NSSlowString/NSSlowString.m

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ - (NSUInteger)length {
2222
return self.stringHolder.length;
2323
}
2424

25-
- (id)copy {
25+
- (id)copyWithZone:(NSZone *)unused {
2626
return self;
2727
}
2828

test/stdlib/TestNSString.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ class TestNSString : TestNSStringSuper {
6060
func test_unpairedSurrogates() {
6161
let evil = getNSStringWithUnpairedSurrogate();
6262
print("\(evil)")
63+
print(evil.data(using: .utf8))
6364
}
6465

6566
}

0 commit comments

Comments
 (0)