Skip to content

Commit 60d09ff

Browse files
authored
Merge pull request #85315 from swiftlang/count-mixup
Make sure we don't compare too many bytes if a non-native string being compared to a native one has the same utf16 count but a different utf8 count
2 parents 05a3216 + a23ed0d commit 60d09ff

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

stdlib/public/core/StringStorageBridge.swift

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,12 @@ extension _AbstractStringStorage {
178178
// CFString will only give us ASCII bytes here, but that's fine.
179179
// We already handled non-ASCII UTF8 strings earlier since they're Swift.
180180
if let asciiEqual = unsafe withCocoaASCIIPointer(other, work: { (ascii) -> Bool in
181-
return unsafe (start == ascii || (memcmp(start, ascii, self.count) == 0))
181+
// otherUTF16Length is the same as the byte count here since it's ASCII
182+
// self.count could still be utf8
183+
if count != otherUTF16Length {
184+
return false
185+
}
186+
return unsafe (start == ascii || (memcmp(start, ascii, otherUTF16Length) == 0))
182187
}) {
183188
return asciiEqual ? 1 : 0
184189
}

test/stdlib/StringBridge.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,4 +195,11 @@ StringBridgeTests.test("lengthOfBytes(using:)") {
195195
expectEqual(utf8AsMacRomanLen, 43)
196196
}
197197

198+
StringBridgeTests.test("Equal UTF16 lengths but unequal UTF8") {
199+
let utf8 = "чебурашка@ящик-с-апельсинами.рф" //Native, UTF16 count: 31, UTF8 count: 58
200+
let nsascii = "2166002315@874404110.1042078977" as NSString //Non-native, UTF16 count: 31, UTF8 count: 31
201+
let nsutf8 = String(decoding: utf8.utf8, as: UTF8.self) as NSString //bridged native
202+
expectFalse(nsutf8.isEqual(nsascii))
203+
}
204+
198205
runAllTests()

0 commit comments

Comments
 (0)